【问题标题】:update state from child in React在 React 中从子级更新状态
【发布时间】:2017-06-27 00:00:07
【问题描述】:

我正在尝试创建一个菜单,用户应在其中创建角色详细信息,但我在通过子项的输入更新选项状态时遇到问题。

var Name = React.createClass({
  render: function(){
    return(
        <input type="text"/>
    )
  }
});

var Options = React.createClass({   
  getInitialState: function(){
    return{
        name: ''
    }
  },
  render: function(){
    return (
        <div>
            Name: <Name onChange={this.updateName} value={this.state.name} />
        </div>
    )
  },
  updateName: function(evt){
    this.setState({
        name: evt.target.value
    });
  }
});

如何使用来自 Name 的输入更新选项状态?

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

您还需要 Name 组件上的 onChange 函数,它将值发送到父组件

试试这个:

var Name = React.createClass({
  onUpdate: function(evt) {
      this.props.onChange(evt);
  }

  render: function(){
    return(
        <input type="text" onChange={this.onUpdate} value={this.props.value}/>
    )
  }
});

var Options = React.createClass({   
  getInitialState: function(){
    return{
        name: ''
    }
  },
  render: function(){
    return (
        <div>
            Name: <Name onChange={this.updateName} value={this.state.name} />
        </div>
    )
  },
  updateName: function(evt){
    this.setState({
        name: evt.target.value
    });
  }
});

【讨论】:

    【解决方案2】:

    Component Communication in React

    请参阅此链接以了解 React 组件之间的通信方式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多