获取孩子的道具点击父组件

  • 本文关键字:组件 孩子 获取 reactjs
  • 更新时间 :
  • 英文 :


我有父母ButtonGroup组件和孩子buttonItem组件:

//ButtonGroup Component (Parent)
clicky(){
 //capture the props of the clicked button, ie, caption and disabled here.
}
render() {
  return (
    <div onClick={this.clicky}>
      {this.props.children}
    </div>
  )
}
//buttonItem component: 
render() {
  return (
    <button disabled={this.props.disabled}>{this.props.caption}</button>
  )
}
//final render
<ButtonGroupComponent>
  <buttonItem caption="Nothing"/>
  <buttonItem caption="Something" disabled={true}/>
  <buttonItem caption="Refresh"/>
</ButtonGroupComponent>

从上面的代码中,我有什么方法可以捕获单击儿童buttonItem的道具?

在您的情况下,您需要将this.props.children与自定义道具合并。因此,我建议您使用React.Children进行操作。顺便说一句,在添加新的道具后,您需要返回这个孩子,因此clonelement将为您提供帮助。

内部导入部分的buttongroupcomponent:

import React, { Children, Component, cloneElement } from 'react';

它的渲染功能看起来像这样:

render() {  
    const childrenWithCustomHandler = Children.map(this.props.children, itemChild => {
       // Arguments of cloneElement (component, [customProps], [customChildren])
       return cloneElement(itemChild, { onClickItem: this.clicky })
     }
    );
    return <div>{childrenWithCustomHandler}</div>;
  }

buttonItem组件的代码看起来像:

 return (
    <button
      disabled={this.props.disabled}
      onClick={() => {
        this.props.onClickItem({ ...this.props });
      }}
    >
      {this.props.caption}
    </button>
  )

我使用传播操作员克隆对象,因此,如果您想更改clicky功能中的道具,则不会渲染孩子。

最新更新