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

转载于:https://www.cnblogs.com/PengZhao-Mr/p/11002869.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值