【发布时间】:2019-11-08 14:17:56
【问题描述】:
我正在尝试创建一个 React 类,其实例的状态更改会影响其子组件的道具。如果子组件在父实例的 render() 方法中实例化,则很容易实现。但是,有没有一种方法可以将父实例的状态值传递给 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>
);
}
}
【问题讨论】:
-
您应该查看
React.Children.map或React.Children.forEachreactjs.org/docs/react-api.html#reactchildrenmap -
你能把问题说得更清楚吗
标签: javascript reactjs ecmascript-6 setstate