zoukankan      html  css  js  c++  java
  • 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();
      };
         
  • 相关阅读:
    低于时钟频率的任意频率生成(相位累加器)
    verilog实现奇数倍分频
    No.135 Candy
    No.42 Trapping Rain Water
    No.149 Max Point on a Line
    No.147 Insertion Sorted List
    No.21 Merge Two Sorted List
    No.88 Merge Sorted Array
    No.148 Sort List
    No.206 Reverse Linked List
  • 原文地址:https://www.cnblogs.com/PengZhao-Mr/p/11002869.html
Copyright © 2011-2022 走看看