Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 - react - via callback function

https://codepen.io/silentarrowz/pen/GEMQEP?editors=0010

and here's the code

class App extends React.Component{
    constructor(props){
      super(props);
      this.state={
        input:'this is the input for now'
      }
   //this.handleInput=this.handleInput.bind(this);   
    }

    handleInput(x){
      this.setState({
        input:x
      });
      alert(this.state.input);
    }

  render(){
    return(
      <div>
        <h1>Passing props from Child to Parent Component</h1>
        <Child getInput={this.handleInput} />
        here's the input: {this.state.input}
        </div>
    );
  }
 }

class Child extends React.Component{
  constructor(){
    super();
    this.state={
      text:''
        }
    }
  passingProps(e){
    var newInput=e.target.value;
    //alert(newInput);
   this.setState({
     text:newInput
    });
  this.props.getInput(this.state.text);
  }

  render(){
    return(
      <div>
      <input type="text" placeholder="please input a name..." onChange={this.passingProps} />

        </div>

    )
  }
}

ReactDOM.render(
  <App/>,
  document.getElementById('app')
);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
253 views
Welcome To Ask or Share your Answers For Others

1 Answer

There are a couple of issues.

1) You have to bind passingProps

constructor(){
    super();
    this.state={
      text:''
    }
    this.passingProps = this.passingProps.bind(this);
}

2) this.setState is asynchronous, so it's not guaranteed that this.state.text will be set to the value you want by the time you pass it to this.props.getInput. You can either do

this.props.getInput(newInput)

or

this.setState({ text: newInput }, () => {
  this.props.getInput(this.state.text);
})

to resolve that issue.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...