react中父子组件的传参及相互调用方法

父子组件间传参数及相互调用方法

//父组件
export default class Parents extends Component {
	eat = (food) => {
		//接受子页面的参数
		console.log("去吃"+food);
		//调用子页面的方法
		this.child.replay();
		//方法二  使用ref调用子组件方法
		this.child2.replay();
	}
	onRef = (ref) => {
		//将父页面的child指向子组件
		this.child = ref;
	}
	render(){
		//子组件通过主动调用onRef(啥名称都可以)可以把this传给父组件
		//ref方法可以接收一个回调函数,表示子组件加载完成后执行的方法,回调函数的参数即为子组件的this
		//this.child2相当于子组件的this
		<Child name="小明" eat={this.eat} onRef={this.onRef} ref={ref => this.child2 = ref} />
	}
	
}

//子组件
export default class Child extends Component {
	componentDidMount() {
	    //获取父页面的参数
	    const { name } = this.props;
	    //调用父页面的方法
	    this.props.eat("小龙虾");
	    //将自身的this通过onRef传给父页面
	    this.props.onRef(this);
	}
	replay = () => {
		console.log("ok");
	}
}
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值