我有父母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
功能中的道具,则不会渲染孩子。