React 父組件觸發子組件事件


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM