I have created a react component which is the modal wrapper only. The content is passed by this.props.children. In the content I have a button, clicking it should pass an event to the parent.
Here is the render part of modal wrapper code
<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>
It is not so different just passing a callback handler without using {this.props.children}
. Am I missing something?
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>
You need do it using React.children
{React.Children.map(children, child => React.cloneElement(child, {
...this.pros,
onClick: () => console.log("click")
}), null)}
This a really good post about childrens on React:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.