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

时间:2018-08-17 14:01:06

标签: javascript reactjs children preact

我创建了一个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>

2 个答案:

答案 0 :(得分:0)

不使用genes = ['gene' + str(i) for i in range(1,101)] wt = ['wt' + str(i) for i in range(1,6)] ko = ['ko' + str(i) for i in range(1,6)] data = pd.DataFrame(columns=[*wt,*ko],index = genes) #create random data for gene in genes: data.loc[gene,'wt1':'wt5'] = np.random.poisson(lam=rd.randrange(10,10000),size=5) data.loc[gene,'ko1':'ko5'] = np.random.poisson(lam=rd.randrange(10,10000),size=5) print(data.head()) 而传递回调处理程序也没什么不同。我想念什么吗?

{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"));

答案 1 :(得分:0)

您需要使用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/