简体   繁体   中英

update state from child in React

I'm trying to create a menu where the user should create a character details but I'm having an issue to update the Options states through an input of a child.

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

How can I go about updating the Option states using the input from Name?

you need onChange function on the Name component as well, that sends the value to the parent component

Try this:

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

Component Communication in React

Refer this link to know what are the ways to communicate between React components.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM