Parent组件
import React from "react";
import Child from "./component/Child";
class Parent extends React.Component {
render() {
return (
<div>
我是父组件
<Child childEvevnt={this.childEvevnt} />
<button onClick={this.triggerEvevt}>触发子</button>
</div>
);
}
// 此事件接收子对象
childEvevnt = childDate => {
this.$child = childDate;
};
// 父组件触发子组件的事件
triggerEvevt = () => {
this.$child.alertEvevnt();
};
}
export default Parent;
child组件
import React from "react";
class Child extends React.Component {
render() {
return <div>我是子组件</div>;
}
componentDidMount() {
this.props.childEvevnt(this);
}
// 父组件要触发的事件
alertEvevnt = () => {
alert("父呼唤我呢!!");
};
}
export default Child;
注意点:
1.使用箭头函数,小心this指向有差错
()=> { }
2.父组件通过props传参把子组件对象接收过来
<Child childEvevnt={this.childEvevnt} />
3.子组件内部进行传递
componentDidMount() {
this.props.childEvevnt(this);
}
4.父组件把接收过来的子对象绑定到父自定义事件上
childEvevnt = childDate => {
this.$child = childDate;
};
5.父组件内部触发子组件的事件
this.$child 上有了子组件的事件
6.触发
triggerEvevt = () => {
this.$child.alertEvevnt();
};

