Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

javascript - How to access one component's state from another component

How do I access one component's state in another component? Below is my code and I'm trying to access the state of component a in component b.

var a = React.createClass({
    getInitialState: function () {
        return {
            first: "1"
        };
    },

    render: function () {
        // Render HTML here.
    }  
});

var b = React.createClass({
    getInitialState: function () {
        return {
            second: a.state.first
        };
    },

    render: function () {
        // Render HTML here.
    }  
});

But I'm not getting anything.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Even if you try doing this way, it is not correct method to access the state. Better to have a parent component whose children are a and b. The ParentComponent will maintain the state and pass it as props to the children.

For instance,

var ParentComponent = React.createClass({
  getInitialState : function() {
    return {
      first: 1,
    }
  }

  changeFirst: function(newValue) {
    this.setState({
      first: newValue,
    });
  }

  render: function() {
   return (
     <a first={this.state.first} changeFirst={this.changeFirst.bind(this)} />
     <b first={this.state.first} changeFirst={this.changeFirst.bind(this)} />
   )
 }
}

Now in your child compoenents a and b, access first variable using this.props.first. When you wish to change the value of first call this.props.changeFirst() function of the ParentComponent. This will change the value and will be thus reflected in both the children a and b.

I am writing component a here, b will be similar:

var a = React.createClass({

  render: function() {
    var first = this.props.first; // access first anywhere using this.props.first in child
    // render JSX
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...