[英]How do I attach multiple event listeners to the same event of a child component from its parent component in React?
I'm creating a React component (parent) that receives a link, button, or other React component (child) as a property, and I want to attach an additional click handler to the passed-in component. 我正在创建一个React组件(父),它接收一个链接,按钮或其他React组件(子)作为属性,我想附加一个单击处理程序到传入的组件。 This child component usually already has a click handler defined, so I can't just add onClick
to it using React.cloneElement. 这个子组件通常已经定义了一个单击处理程序,所以我不能只使用React.cloneElement向它添加onClick
。 Also, sometimes the child component's click handler prevents event propagation to the parent component, so I can't just attach the click listener to the parent and allow the event to bubble up. 此外,有时子组件的单击处理程序会阻止事件传播到父组件,因此我不能将单击侦听器附加到父组件并允许事件冒泡。
Edit: The parent/child relationship and how/where the extra event listener should be attached makes this question slightly different from other questions I've seen, where the answer is to pass a callback (or array of callbacks) into the child component. 编辑:父/子关系以及应该附加额外事件监听器的方式/位置使得这个问题与我看到的其他问题略有不同,其中答案是将回调(或回调数组)传递给子组件。 I do not have access to alter the child component's API. 我没有权限更改子组件的API。
Here's some sample code: 这是一些示例代码:
export default class ParentComponent extends React.Component {
constructor(props) {
super();
this.handleClick = this.handleClick.bind(this);
}
handleClick(event) {
// do something (this is not working)
}
render() {
let { childComponent } = this.props;
return (
<div>
{React.cloneElement(childComponent, {
onClick: this.handleClick
})}
</div>
)
}
}
ParentComponent.PropTypes = {
childComponent: PropTypes.element
};
The best way I've found to do this so far uses refs and findDOMNode, as suggested in the comments above. 到目前为止,我发现这样做的最好方法是使用refs和findDOMNode,如上面的评论所示。 Once you have a reference to the child component's DOM node, you can add a regular event listener when the parent component gets mounted: 一旦引用了子组件的DOM节点,就可以在挂载父组件时添加常规事件监听器:
export default class ParentComponent extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
this.childComponentRef.addEventListener('click', function() {
// do something (this works!)
}, false);
}
render() {
let { childComponent } = this.props;
return (
<div>
{React.cloneElement(childComponent, {
ref: (childComponentRef) => {
this.childComponentRef = ReactDOM.findDOMNode(childComponentRef);
}
})}
</div>
)
}
}
ParentComponent.PropTypes = {
childComponent: PropTypes.element
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.