简体   繁体   English

如何在反应中提升状态两个级别?

[英]How to lift state two levels up in react?

Following this example by React. 在React的这个示例之后。

I want to be able to lift states two levels up. 我希望能够将状态提升两个级别。 Meaning, when an event occurs at the lower level component, I want it to affect the state two levels up. 意思是,当事件发生在较低级别的组件上时,我希望它影响两个级别以上的状态。 How should I do this? 我应该怎么做? Is this even recommended? 甚至推荐吗?

For example, Component A is the parent of Component B, Component B is the parent of Component C. A -> B -> C. 例如,组件A是组件B的父级,组件B是组件C的父级。A-> B->C。

In A, 在一个,

handleChange = (e) => {console.log(e)}
<B onChange={handleChange}/>

In B, 在B中

handleChange = (e) => this.props.onChange(e)
<C onChange={this.handleChange}/>

In C, 在C中

handleChange = (e) => this.props.onChange(e)
<button onClick={this.handleChange}></button>

Is there a better way to do this? 有一个更好的方法吗?

Using your example A->B->C here. 在这里使用示例A-> B-> C。 You should create a setter in A. 您应该在A中创建一个二传手。

state of A: A状态:

this.state={ stateA: "whatever"}

function in A: 在A中的功能:

setStateA(newVal){
    this.setState({stateA: newVal});
}

Now pass it as property to B 现在将其作为属性传递给B

<B setStateA={this.setStateA} />

In B: 在B中:

<C setStateA={this.props.setStateA} />

In C: 在C中:

// some code
this.props.setStateA("a new value");
//some code

I think this is the best way to do it. 我认为这是最好的方法。 Passing function as property to children. 将功能作为属性传递给孩子。 Hope it helps. 希望能帮助到你。

You don't need to recreate the function in the B component, simply passing it along will work. 您无需在B组件中重新创建函数,只需将其传递即可。

B will simply look like B看起来就像

<C onChange={this.props.onChange}/>

Same for C where you can directly attach the event the props to onClick. 与C相同,您可以在C上将道具直接附加到onClick。

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

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