【问题标题】:Is it possible to pass variables (props/states) to an already-created React instance [duplicate]是否可以将变量(道具/状态)传递给已经创建的 React 实例 [重复]
【发布时间】: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>
    );
  }
}

【问题讨论】:

标签: javascript reactjs ecmascript-6 setstate


【解决方案1】:

如果我理解正确,您正在尝试像这样为孩子添加额外的属性:

<Parent>
   <Child/>
</Parent>

但是 Parent 想要像这样渲染它的孩子:

<Child val={1}/>

解决方案是React.cloneElement

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

【讨论】:

  • 不确定cloneElement 是否应该这样使用,但它可以工作,小提琴:jsfiddle.net/wy1zh8rx
猜你喜欢
  • 2019-12-04
  • 2016-01-07
  • 2018-08-13
  • 2023-03-24
  • 1970-01-01
  • 2021-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多