从 parent 更新组件的 属性

Update a property of a component from the parent

我一直在尝试更改 child 的 属性 但失败了。我已经尝试了 React 的大部分生命周期方法,但其中 none 似乎有效(didMount propsUpdate 等)。

如有任何帮助,我们将不胜感激

http://codepen.io/yogainalift/pen/KMPvNz

var Field = React.createClass({
  getInitialState: function() {
    return {
      message: this.props.setMessage || 'should change this one'
    }
  },

  render() {
    return (
      <div>
        {this.state.message}
      </div>
    )
  }
});

var App = React.createClass({
  getInitialState: function() {
    return {
      inputField: ''
    }
  },

  handle(event) {
    console.log(event.target.value);
    this.setState({
      inputField: event.target.value
    })
  },

  render() {
    return (
      <div>
        <input type='text' placeholder='changing this text' onChange={this.handle}/>
        <Field setMessage={this.state.inputField} />
      </div>
    )
  }
});

ReactDOM.render(<App />, document.getElementById('app'));

根据我从你的问题中了解到的情况,你试图让 Field 呈现与输入相同的效果,对吗?

您的 Field 组件正在使用状态来呈现其内容

<div>
     {this.state.message}
</div>

你应该使用

<div>
    {this.props.setMessage}
</div>

您还可以使用 componentWillReceiveProps 生命周期方法为 Field 设置新状态。 代码如下所示:

componentWillReceiveProps: function(nextProps) {
  this.setState({
    message: nextProps.setMessage || 'should change this one'
  });
}

希望对您有所帮助。