在反应中将数据传递给父组件 [英] Passing data to parent component in react

查看:35
本文介绍了在反应中将数据传递给父组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在子组件中创建了表单.使用 jquery ajax 方法提交该表单后 ($.ajax) 我正在以 json 格式检索一些数据.我想将该数据置于父组件的状态中.那么,react.js 中是否有任何方法可以将值或数据从子组件传递到其父组件?

谢谢..

解决方案

在没有某种 Flux 实现的情况下做到这一点的方法是在父元素上创建一个函数来处理来自子元素的响应/数据并传递该函数作为道具.然后从孩子那里调用那个函数.像这样:

家长:

handleResponse(data) {控制台日志(数据)}使成为() {返回(<div><子句柄响应={this.handleResponse}/>

);}

然后在孩子中:

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

这一切都假设 ES6 语法.使用 ES5,您将不得不使用 bindvar that = this 来正确地确定所有内容的范围.

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..

解决方案

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.

这篇关于在反应中将数据传递给父组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆