How to pass state back to parent in React?

后端 未结 7 1415
时光说笑
时光说笑 2020-12-05 04:08

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 pa

7条回答
  •  日久生厌
    2020-12-05 04:57

    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 (
            
    ); } }

    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.

提交回复
热议问题