父子组件间传参数及相互调用方法
//父组件
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");
}
}