繁体   English   中英

如果我在React中使用this.props.children,如何传递按钮单击事件

[英]How do I pass button click event if I am using this.props.children in React

我创建了一个仅是模式包装器的react组件。 内容由this.props.children传递。 在内容中,我有一个按钮,单击它应该将事件传递给父级。

这是模式包装器代码的渲染部分

 <div class="modal-container-backdrop"> <div class="modal-container-overlay" onClick={this.onOverlayClick}> <div class="modal-container-content" style={{padding: this.props.isCloseable ? '30px 20px' : '0px 0px' }} onClick={this.onContentClick} style={{width: this.props.modalWidth ? this.props.modalWidth+'px' : '320px'}}> {this.props.isCloseable ? <div class="modal-container-close-img" onClick={this.onCloseImgClick}></div> : null } {this.props.children} </div> </div> </div> 

不使用{this.props.children}传递回调处理程序也没什么不同。 我想念什么吗?

 class App extends React.Component { handleClick = () => alert("clicked"); render() { return ( <div> <Child> <button onClick={this.handleClick}>Click</button> </Child> </div> ); } } class Child extends React.Component { render() { return ( <div> {this.props.children} </div> ) } } ReactDOM.render(<App />, document.getElementById("root")); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div> 

您需要使用React.children

      {React.Children.map(children, child => React.cloneElement(child, {
        ...this.pros,
        onClick: () => console.log("click")
      }), null)}

这是一个关于儿童在React上的非常好的帖子:

https://mxstbr.blog/2017/02/react-children-deepdive/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM