How to pass state back to parent in React?

2019-02-22 08:50发布

问题:

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>
    )

回答1:

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}/>


回答2:

Here is an example of how we can pass data from child to parent (I had the same issue and use come out with this )

On parent, I have a function (which I will call from a child with some data for it)

handleEdit(event, id){ //Fuction
    event.preventDefault();  
    this.setState({ displayModal: true , responseMessage:'', resId:id, mode:'edit'});  
 } 

dishData = <DishListHtml list={products} onDelete={this.handleDelete} onEdit={(event, id) => this.handleEdit(event, id)}/>;

At the child component :

<div to="#editItemDetails" data-toggle="modal" onClick={(event)=>this.props.onEdit(event, listElement.id) }
                        className="btn btn-success">