简体   繁体   中英

React how to update another component's state?

I am pretty new to react, trying to make some components work. I have

    ObjectA:React.createClass({
        propTypes: {
           ...

        },

        getInitialState: function() {
            return {
                myState: null
            }
        },

        updateMyState: function(value) {
           this.setState({
               myState: value
           })
        }

        render: function() {
            return (<div className="my-class">'hello' +{this.state.myState}</div>);
          }
    });

    ObjectB:React.createClass({
            propTypes: {
               ...

            },

            render: function() {
                return (<div className="my-class"><ObjectA / >

            </div>);
            }
        });

I'd like to update ObjectA's state from ObjectB. How could I in ObjectB call ObjectA's updateMyState method? Thanks!

The basic idea of React is the unidirectional data flow. That means that data is only shared downwards from an ancestor component to its children via the child's properties. We leave Flux like architectures and event emitters out of the equation for this simple example as it's not necessary at all.

The ONLY way then to change a component's state from the outside is changing the props it receives in the parent's render method. so myState would actually live in ObjectB and be given to ObjectA as property. In your example that would look like this:

ObjectA:React.createClass({
    propTypes: {
       ...

    },

    render: function() {
        return (<div className="my-class">'hello' +{ this.props.name }</div>);
      }
});

ObjectB:React.createClass({
    propTypes: {
       ...

    },

    getInitialState: function() {
        return {
            name: null
        }
    },

    onNameChange: function(newName) {
        this.setState({ name: newName })
    },

    render: function() {
        return (
            <div className="my-class">
                <ObjectA name={ this.state.name } />
            </div>
        );
    }
});

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