reactjs - 在父组件中获取子组件的 onClick 道具
问题描述
我有一个父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来操作它。顺便说一句,在添加新道具后,您需要返回这个孩子,所以 cloneElement会帮助您。
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>
)
我使用Spread操作符来克隆对象,因此如果您想更改clicky
函数中的道具,则不会呈现子对象。
推荐阅读
- swift - physicsBody:无法创建物理体(模拟器错误)
- python - PCollection 到数组 - 如何将标题动态输入到 WriteToText PTransform?
- python - 文件在 Python 尝试的 else 块中有零行,除了代码
- python - Django:验证表单中的文件字段
- reactjs - 如何解释 React Profiler 火焰图?
- android - 设置材质选项卡布局的样式
- r - R:从可能值列表中生成数据框
- r - 从R中的字符串中提取x和y值
- mongodb - MongoDB ObjectId 与 find() 中的字符串
- postgresql - PostgreSQL - 删除重复记录 - 错误:范围表条目过多