我希望抽象出事件监听器在子组件上的绑定(bind)。或者允许组件改变 child 的 Prop 。
我想在 JSX 中表达组件,例如
<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>
这是增强的单选或复选框分组。
现在我想增强输入以自动通知父组件存储状态的更改。
我希望这是可能的
{React.Children.toArray(this.props.children).map((Child => (<Child onClick={() => console.log("yea!")} />)))}
或更简单地说
{this.props.children.map((Child => (<Child onClick={() => console.log("yea!")} />)))}
但是我收到 typescript 错误
JSX element type 'Child' does not have any construct or call signatures
使用
"react": "^16.8.6",
"typescript": "^3.5.2"
这可能吗,还是有其他方法可以实现这一目标?
最佳答案
您可以使用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>
)
}
关于javascript - 增强/操纵 react child Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56861769/