简体   繁体   English

如何从另一个组件访问一个组件的状态

[英]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 .下面是我的代码,我正在尝试访问组件b中组件a的状态。

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.但我什么也得不到。

Even if you try doing this way, it is not correct method to access the state .即使您尝试这样做,访问state也不是正确的方法。 Better to have a parent component whose children are a and b .最好有一个子组件是ab的父组件。 The ParentComponent will maintain the state and pass it as props to the children. ParentComponent将维护state并将其作为道具传递给孩子。

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 .现在在您的子组件ab中,使用this.props.first访问first变量。 When you wish to change the value of first call this.props.changeFirst() function of the ParentComponent .当您希望更改first调用ParentComponentthis.props.changeFirst()函数的值时。 This will change the value and will be thus reflected in both the children a and b .这将改变值,因此将反映在孩子ab中。

I am writing component a here, b will be similar:我在这里写组件ab将是相似的:

var a = React.createClass({

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

If two components need access to the same state they should have a common ancestor where the state is kept.如果两个组件需要访问相同的状态,它们应该有一个共同的祖先来保存状态。

So component A is the parent of B and C. Component A has the state, and passes it down as props to B and C. If you want to change the state from B you pass down a callback function as a prop.所以组件 A 是 B 和 C 的父组件。组件 A 具有状态,并将其作为道具传递给 B 和 C。如果要从 B 更改状态,则将回调函数作为道具传递。

I would suggest you use a state manager like Redux (personal favorite), MobX reflux, etc to manage your state.我建议你使用像 Redux(个人最喜欢的)、MobX 回流等状态管理器来管理你的状态。

How these works is they allow you to contain all shared state in one state storage (called a store), and whatever component needs access to a part of that shared state, it will just get it from the store.这些工作原理是它们允许您将所有共享状态包含在一个状态存储(称为存储)中,并且任何组件需要访问该共享状态的一部分,它只会从存储中获取它。

It looked very hard to get started with but once you get over the small challenges, get 2 or 3 "wtf's" out of the way.它看起来很难开始,但是一旦你克服了小挑战,就可以摆脱 2 或 3 个“wtf”。 It gets easier.它变得更容易。

Take a look here: http://redux.js.org/看看这里: http ://redux.js.org/

EDIT: Redux is good but the boilerplate code is really a turn off... for those of you looking for a simpler, more magical (this can be good and bad) solution use mobx : https://mobx.js.org/编辑: Redux 很好,但样板代码确实是一个关闭...对于那些寻找更简单、更神奇(这可能是好也可能是坏)解决方案的人来说,使用 mobx: https ://mobx.js.org/

in the child component create function that sets the state:在子组件中创建设置状态的函数:

changeTheState(){
    this.setState({something:"some value"})
}

and in parent component give the child a ref as following:并在父组件中给孩子一个参考,如下所示:

<Child ref={component => this._child = component}/>

then in parent make a function to access the changeTheState()然后在 parent 中创建一个函数来访问 changeTheState()

parentFunction(){
    this._child.changeTheState();
}

and just use the parentFunction.并且只需使用 parentFunction。

If you have A and B component where B is a child of A, you can pass a function to change the state of A though props to B.如果您有 A 和 B 组件,其中 B 是 A 的子级,则可以通过向 B 传递一个函数来更改 A 的状态。

function B(props) {
    return <button onClick={props.changeA} />
}

class A extends React.Component {

    //constructor
    //pass this function to B to change A's state
    handleA() {
        this.setState({});
    }

    render() {
        return <B changeA={() => this.handleA()} />
    }
}

Take a look at React Context看看React 上下文

Context provides a way to pass data through the component tree without having to pass props down manually at every level. Context 提供了一种通过组件树传递数据的方法,而无需在每个级别手动传递 props。

You can also update Context from a nested component if required.如果需要,您还可以从嵌套组件更新 Context

Okay, everyone. 好的,大家好 Please, lets take functional programming seriously.. So going back to answer your question. 请让我们认真对待函数式编程。所以回过头来回答你的问题。 create a props thats a function probably called this.props.sendValue(this.state) , and initialize the function in the parent component. 创建一个可能称为this.props.sendValue(this.state)的函数的this.props.sendValue(this.state) ,并初始化父组件中的函数。 <NewComponent><Component sendValue={(args)=> return(args)}/></NewComponent>

LOL. 大声笑。 Haven't actually tried this but this should be the solution to your question 实际上没有尝试过,但这应该是你问题的解决方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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