javascript - Enhancing/manipulating react children props
问题描述
I was hoping to abstract away the binding of event listeners on children components. Or allow a component to alter props of children.
I'm wanting to express the components in JSX like
<DocumentScreen name="Type">
<DocumentInput value="L" name="(=learner)" icon="lerners.svg" />
<DocumentInput value="P" name="(=probationary)" icon="probationary.svg" />
<DocumentInput value="Full" icon="full.svg" />
</DocumentScreen>
Which is an enhanced radio or checkbox grouping.
Now I want to enhance the inputs to automagically notify the parent component of changes to store state.
I was hoping this would be possible
{React.Children.toArray(this.props.children).map((Child => (<Child onClick={() => console.log("yea!")} />)))}
Or more simply
{this.props.children.map((Child => (<Child onClick={() => console.log("yea!")} />)))}
But I get a typescript error
JSX element type 'Child' does not have any construct or call signatures
Using
"react": "^16.8.6",
"typescript": "^3.5.2"
Is this possible or is there another way to achieve this?
解决方案
You can use cloneElement
https://reactjs.org/docs/react-api.html#cloneelement
render() {
return (
<div>
{React.Children.map(this.props.children, child => {
return React.cloneElement(child, {
onClick : () => console.log("yea!")
})
})}
</div>
)
}
推荐阅读
- python - 如何创建一个 3D 数组,其中第 k 个元素是一个 2x2 矩阵,我为其定义了向量中的系数
- vb.net - 如何在所有表单上更改相同的背景颜色?
- java - 添加注释以自动指示字段的顺序
- azure - Azure 表存储 (412) 前提条件失败
- angular - Angular:父通过服务不工作订阅子组件的更改
- javascript - 从不同项目运行时,Flask 会加载相同的 index.js 文件
- android - ANDROID:错误膨胀类 android.support.design.widget.AppBarLayout
- html - 如何在我的文本上应用 z-index 以将其浮动在我的图像上
- python - 为什么我会陷入无限循环?
- java - 泛型中的类型擦除和代码生成