How to pass state back to parent in React?

对着背影说爱祢 提交于 2019-11-29 03:34:39

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

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">
Aftab22

Simple Steps:

  1. Create a component called Parent.
  2. In Parent Component create a method that accepts some data and sets the accepted data as the parent's state.
  3. Create a component called Child.
  4. Pass the method created in Parent to child as props.

  5. Accept the props in parent using this.props followed by method name and pass child's state to it as argument.

  6. The method will replace the parent's state with the child's state.

In React you can pass data from parent to child using props. But you need a different mechanism to pass data from child to parent.

Another method to do this is to create a callback method. You pass the callback method to the child when it's created.

class Parent extends React.Component {
myCallback = (dataFromChild) => {
    //use dataFromChild
},
render() {
    return (
        <div>
             <ComponentA callbackFromParent={this.myCallback}/>
        </div>
    );
  }
}

You pass the decisionPage value from the child to the parent via the callback method the parent passed.

     class ComponentA extends React.Component{
          someFn = () => {
            this.props.callbackFromParent(decisionPage);
          },
          render() {
            [...]
          }
     };

SomeFn could be your handleClick method.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!