react中我们都知道组件间的通信几乎都是通过props或者回调函数形式进行传递(子组件调用获取父组件),但是实际开发中会因为组件划分或者业务需求,不得不在父组件中调用子组件的方法(操作父组件来调用子组件的方法,来改变子组件的state)。
import react, {Component} from 'react';
class Parent extends Component {
onRef = (e) => {
this.child = e;//将子组件this赋值给父组件的child
}
parentFunction = () => {
this.child.childFunction();//父组件调用子组件方法
}
render (){
return(
<div>
<Child onRef={this.onRef}/>//自定义子组件属性传递给子组件
<button onClick={()=>this.parentFunction()}/>
</div>
)
}
}
import react ,{Component} from 'react';
class Child extends Compontnt {
childFunction = () => {
alert('success!');
}
componentDidMount(){
//判断逻辑等等
this.props.onRef(this);//将子组件的this传给父组件中<Child/>定义的的onRef的onRef方法;
}
}
项目中未集成Redux或Mobx可用以上方法在父组件中调用子组件方法,下篇会讲解reacr16.3中新增createRef()