passing data from child to parent component - react - via callback function

后端 未结 6 1373
花落未央
花落未央 2020-12-06 07:40

passing data from child to parent component via callback function but somehow it\'s not working. what am I doing wrong here? passing data from child to parent component - re

6条回答
  •  鱼传尺愫
    2020-12-06 08:00

    In your Child Component, you have written following code:

    passingProps(e){
      var newInput=e.target.value;
      //alert(newInput);
      this.setState({
         text:newInput
      });
      this.props.getInput(this.state.text);
    }
    

    The issue is due to the asynchronous behaviour of setState function. It means you can not call setState on one line and expect its updates on next line. Use the callback function of setState to call the function of parent component just like this:

    passingProps(e){
      var newInput=e.target.value;
      //alert(newInput);
      this.setState({ text: newInput }, () => {
         this.props.getInput(this.state.text);
      })
    }
    

    Same thing is happening in handleInput function of App component.

提交回复
热议问题