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();
};

