加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

React 父组件触发子组件事件

发布时间:2020-12-15 16:20:32 所属栏目:百科 来源:网络整理
导读: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} 触发子 / butto

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读