如何将状态传回给React中的父项? [英] How to pass state back to parent in React?

查看:107
本文介绍了如何将状态传回给React中的父项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有提交按钮的表单。
这个表单调用一个函数onclick,将某些事情的状态从false设置为true。
然后我想把这个状态传递给父类,这样如果它是真的,它就呈现componentA,但是如果它是假的,它会呈现componentB。



我在做反应吗?
我知道我需要使用状态或道具,但不知道如何去做。也是这种矛盾的单向流动反应原理??

ComponentA代码:
$ b $

code>< form onSubmit = {this.handleClick}>


handleClick(event){
this.setState({decisionPage:true});
event.preventDefault();
};

控制显示内容的父组件:



< pre< code> return(
< div>
{this.props.decisionPage?
< div>
< LoginPage />
< / div>

< div>
< Decision showThanks = {this.props.showThanks} />
< / div>
}
< / div>


解决方案将 handleClick 传递给父级,并将其作为道具传递给子组件。

 < LoginPage handleClick = {this.handleClick.bind(this)} /> 

现在在子组件中:

 < form onSubmit = {this.props.handleClick}> 

通过这种方式提交表单将直接更新父组件中的状态。这假定您不需要访问子组件中的更新状态值。如果你这样做,那么你可以将状态值从父母传递给孩子作为道具。单向数据流被维护。

 < LoginPage handleClick = {this.handleClick.bind(this)} decisionPage = {this.state.decisionPage} /> ; 


I have a form that has a submit button. That form calls a function onclick that sets the state of something from false to true. I then want to pass this state back to the parent so that if it is true it renders componentA but if it is false it renders componentB.

How would I do that in react? I know I need to use state or props but not sure how to do it. also is this contradicting the one-way flow react principle??

ComponentA code:

<form onSubmit={this.handleClick}>


handleClick(event) {
    this.setState({ decisionPage: true });
    event.preventDefault();
  };

Parent component that controls what it displays:

return (
      <div>
      {this.props.decisionPage ?
        <div>
          <LoginPage />
        </div>
        :
        <div>
          <Decision showThanks={this.props.showThanks}/>
        </div>
      }
      </div>
    )

解决方案

Move handleClick to the parent and pass it to the child component as a prop.

<LoginPage handleClick={this.handleClick.bind(this)}/>

Now in the child component:

<form onSubmit={this.props.handleClick}>

This way submitting the form will update the state in parent component directly. This assumes you don't need to access updated state value in child component. If you do, then you can pass the state value back from the parent to the child as a prop. One-way data flow is maintained.

<LoginPage  handleClick={this.handleClick.bind(this)} decisionPage={this.state.decisionPage}/>

这篇关于如何将状态传回给React中的父项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆