How do I edit multiple input controlled components in React?

后端 未结 9 529
[愿得一人]
[愿得一人] 2020-12-04 09:01

I have a component that stores a contact object as state - {firstName: \"John\", lastName: \"Doe\", phone: \"1234567890} I want to create a form to edit this object but if I

9条回答
  •  半阙折子戏
    2020-12-04 09:36

    There are two ways to update the state of a nested object:

    1. Use JSON.parse(JSON.stringify(object)) to create a copy of the object, then update the copy and pass it to setState.
    2. Use the immutability helpers in react-addons, which is the recommended way.

    You can see how it works in this JS Fiddle. The code is also below:

    var Component = React.createClass({
        getInitialState: function () {
        return ({contact: {firstName: "first", lastName: "last", phone: "1244125"}});
      },
      handleChange: function (key,event) {
        console.log(key,event.target.value);
    
        //way 1 
        //var updatedContact = JSON.parse(JSON.stringify(this.state.contact));
        //updatedContact[key] = event.target.value;
    
        //way 2 (Recommended)
        var updatedContact = React.addons.update(this.state.contact, {
            [key] : {$set: event.target.value}
        });
        this.setState({contact: updatedContact});
      },
      render: function () {
        return (
            
    ); } }); ReactDOM.render( , document.getElementById('container') );

提交回复
热议问题