我正在尝试创建一个反应类,其实例的变化会影响其子女组件的道具。如果子组件是在父实例的渲染方法((方法中实例化的,则很容易意识到它。但是,有没有一种方法可以将父式实例的状态值传递给this.props.Children作为已经建立的React组件传递给render((方法(请参见下面的代码(?
const Child = class extends React.Component{
render(){
return (
<div>
{this.props.val}
</div>
)
}
}
const Parent = class extends React.Component{
constructor(){
this.state = {val: undefined};
this.handleClick = this.handleClick.bind(this);
}
handleClick(e){
this.setState({val: e.nativeEvent.offsetY});
}
render(){
const children = this.props.children.map( child => (
child instanceof Object
? child // how to pass this.state.val to this instance?
: <Child val={this.state.val}></Child> // passing this.state.val is easy
) );
return (
<div>
{children}
</div>
);
}
}
const enhancedParent = class extends React.Component{
render(){
return (
<div>
{this.props.val} // or this.state.val, or anything else that receives this.state.val from its parent
</div>
);
}
}
如果我正确理解,您正在尝试为这样的孩子添加额外的属性:
<Parent>
<Child/>
</Parent>
,但父母想这样培养孩子:
<Child val={1}/>
解决方案是React.cloneElement
。
render(){
return (
<div>
{{React.cloneElement(this.props.children, {
val: this.state.val
})}}
</div>
);
}