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

Categories

0 votes
618 views
in Technique[技术] by (71.8m points)

reactjs - Passing data to parent component in react

I've created on form in child component. After submitting that form using jquery ajax method ($.ajax) I am retriving some data in json format. I want to put that data in my parent component's state. So, is there any method in react.js for passing value or data from child component to its parent component?

Thank you..

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

The way to do this without some kind of Flux implementation is to create a function on the parent element that handles the response/data from the child and pass that function as a prop. Then call that function from the child. Something like this:

Parent:

handleResponse(data) {
  console.log(data)
}

render() {
  return(
    <div>
      <Child handleResponse={this.handleResponse} />
    </div>
  );
}

then in the child:

handleAjax() {
  $.get(url).then( (response) => {
    this.props.handleResponse(response)
  });
}

this all assumes ES6 syntax. Using ES5 you're going to have to use bind or var that = this to scope everything correctly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...