是否可以将变量(属性/状态)传递给已经创建的React实例

时间:2019-06-26 15:18:16

标签: javascript reactjs ecmascript-6 setstate

我正在尝试创建一个React类,其实例的状态更改会影响其子组件的道具。如果在父实例的render()方法中实例化子组件,则很容易实现。但是,有没有一种方法可以将父实例的状态值传递给已实例化的React组件传递给render()方法的this.props.children(请参见下面的代码)?

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>
    );
  }
}

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您正在尝试向子级添加其他属性,如下所示:

<Parent>
   <Child/>
</Parent>

但是Parent希望这样渲染其子代:

<Child val={1}/>

解决方案是React.cloneElement

render(){
    return (
        <div>
            {{React.cloneElement(this.props.children, {
                val: this.state.val
            })}}
        </div>
    );
}