在父组件中点击孩子的道具

时间:2018-04-26 04:53:13

标签: reactjs

我有一个父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
从上面的代码

有什么方法可以捕获点击的孩子{{1}}的道具?

1 个答案:

答案 0 :(得分:0)

在您的情况下,您需要将suggestion与自定义道具合并。所以,我建议您使用React.Children来操作它。 顺便说一句,在添加新道具之后,你需要退回这个孩子,所以cloneElement会帮助你解决这个问题。

ButtonGroupComponent的内部导入部分:

this.props.children

它的渲染功能如下所示:

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

我使用Spread运算符来克隆对象,因此如果您想在 return ( <button disabled={this.props.disabled} onClick={() => { this.props.onClickItem({ ...this.props }); }} > {this.props.caption} </button> ) 函数中更改道具,则不会渲染子项。

相关问题