首页 > 解决方案 > 从父母发送 onMouseDown 给孩子

问题描述

有没有办法将clickevent从父母发送给孩子?

这是我的父组件:

<Component {...props}>
     <Child />
     {props.children}
</Component>

这是子组件:

<Component onMouseDown={e => this.handleClick(e, props)}></Component>

每当单击父组件时,我都想触发我孩子的 handleclick 组件。

提前致谢!

标签: reactjs

解决方案


您可以使用对子组件的引用:

// parent.js

constructor(props) {
  super(props);
  this.child = React.createRef();
}

handleMouseDown = e => {
  this.child.current.handleClick(e, this.props);
}

render() {
  return (
    <Component onMouseDown={this.handleMouseDown} {...props}>
       <Child ref={this.child}/>
       {props.children}
    </Component>
  )
}

推荐阅读