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
189 views
in Technique[技术] by (71.8m points)

javascript - 如何在React中更新父状态(How to update parent's state in React?)

My structure looks as follows:

(我的结构如下所示:)

Component 1  

 - |- Component 2


 - - |- Component 4


 - - -  |- Component 5  

Component 3

Component 3 should display some data depending on state of Component 5. Since props are immutable, I can't simply save it's state in Component 1 and forward it, right?

(组件3应该根据组件5的状态显示一些数据。由于道具是不可变的,我不能简单地将其状态保存在组件1中并转发它,对吗?)

And yes, I've read about redux, but don't want to use it.

(是的,我已经阅读了有关redux的内容,但不想使用它。)

I hope that it's possible to solve it just with react.

(我希望有可能通过反应来解决。)

Am I wrong?

(我错了吗?)

  ask by wklm translate from so

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

1 Reply

0 votes
by (71.8m points)

For child-parent communication you should pass a function setting the state from parent to child, like this

(对于儿童与父母之间的通信,您应该传递一个将状态从父母更改为孩子的函数,如下所示)

 class Parent extends React.Component { constructor(props) { super(props) this.handler = this.handler.bind(this) } handler() { this.setState({ someVar: 'some value' }) } render() { return <Child handler = {this.handler} /> } } class Child extends React.Component { render() { return <Button onClick = {this.props.handler}/ > } } 

This way the child can update the parent's state with the call of a function passed with props.

(这样,孩子可以通过调用通过props传递的函数来更新父母的状态。)

But you will have to rethink your components' structure, because as I understand components 5 and 3 are not related.

(但是您将不得不重新考虑组件的结构,因为据我了解,组件5和3并不相关。)

One possible solution is to wrap them in a higher level component which will contain the state of both component 1 and 3. This component will set the lower level state through props.

(一种可能的解决方案是将它们包装在更高级别的组件中,该组件将同时包含组件1和3的状态。此组件将通过prop设置较低级别的状态。)


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

...