如何从React的子组件中获取值 [英] How to get values from child components in React

查看:87
本文介绍了如何从React的子组件中获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我才刚刚开始使用React,并且在收集子组件中输入的输入值时遇到了麻烦.基本上,我要为正在制作的大型表单创建不同的组件,然后在包含组件中,我想收集我正在调用数据的对象中子代上所有输入的值,然后将收集到的输入发送到POST中. AJAX请求(您可以在我制作的最后一个组件中看到一个示例).当我进入组件内部时,可以很容易地拉出值,但可以从尚未弄清楚的父组件中拉出它们.

So I am just starting to use React and am having trouble gathering the input values of inputs within a child component. Basically, I am creating different components for a large form I am making, then in the encompassing component, I want to collect all the values of inputs on the children in an object I am calling data, and then send that collected input into a POST AJAX request (you can see an example in the last component I made). I can pull the values easily enough when I am inside of the components, but pulling them from the parent component I haven't figured out.

先谢谢了.就在React的痛苦之中,所以关于如何更好地构造它的任何建议,我都很高兴!

Thanks in advance. Just going through the pains right now with React so any recommendations on how to structure this better as well, I am all ears!

这是我的组成部分:

组件一

var StepOne = React.createClass({
  getInitialState: function() {
    return {title: '', address: '', location: ''};
  },
  titleChange: function(e) {
    this.setState({title: e.target.value});
  },
  addressChange: function(e) {
   this.setState({address: e.target.value});
  },
  locationChange: function(e) {
    this.setState({location: e.target.value});
  },
  render: function() {
    return (
      <div className="stepOne">
        <ul>
          <li>
            <label>Title</label>
            <input type="text" value={this.state.title} onChange={this.titleChange} />
          </li>
          <li>
            <label>Address</label>
            <input type="text" value={this.state.address} onChange={this.addressChange} />
          </li>
          <li>
            <label>Location</label>
            <input id="location" type="text" value={this.state.location} onChange={this.locationChange} />
          </li>
        </ul>
      </div>
    );
  }, // render
}); // end of component

第二部分

var StepTwo = React.createClass({
  getInitialState: function() {
    return {name: '', quantity: '', price: ''}
  },
  nameChange: function(e) {
    this.setState({name: e.target.value});
  },
  quantityChange: function(e) {
    this.setState({quantity: e.target.value});
  },
  priceChange: function(e) {
    this.setState({price: e.target.value});
  },
  render: function() {
    return (
      <div>
      <div className="name-section">
        <div className="add">
          <ul>
            <li>
              <label>Ticket Name</label>
              <input id="name" type="text" value={this.state.ticket_name} onChange={this.nameChange} />
            </li>
            <li>
              <label>Quantity Available</label>
              <input id="quantity" type="number" value={this.state.quantity} onChange={this.quantityChange} />
            </li>
            <li>
              <label>Price</label>
              <input id="price" type="number" value={this.state.price} onChange={this.priceChange} />
            </li>
          </ul>
        </div>
      </div>
      </div>
    );
  }
});

收集数据并提交Ajax请求的最终组件

Final component to collect data and submit ajax request

EventCreation = React.createClass({
 getInitialState: function(){
  return {}
},
submit: function (e){
  var self

  e.preventDefault()
  self = this

  var data = {
    // I want to be able to collect the values into this object then send it in the ajax request. I thought this sort of thing would work below:
    title: this.state.title,
  }

  // Submit form via jQuery/AJAX
  $.ajax({
    type: 'POST',
    url: '/some/url',
    data: data
  })
  .done(function(data) {
    self.clearForm()
  })
  .fail(function(jqXhr) {
    console.log('failed to register');
  });
},
render: function() {
    return(
      <form>
        <StepOne />
        <StepTwo />
        // submit button here
      </form>
    );
  }
});

推荐答案

在子组件中定义返回所需数据的方法,然后在渲染子组件时在父组件中定义方法,请在以后定义引用,以供参考.要检索所需的数据,可以在子级上调用这些方法.

Define methods in the child components that return the data that you want and then in the parent component when you are rendering the children, define refs so later on when you want to retrieve the data that you need you can call those method on the children.

StepOne = React.createClass({
    getData: function() {
        return this.state;
    }
});

StepTwo = React.createClass({
    getData: function() {
        return this.state;
    }
});

EventCreation = React.createClass({
    submit: function() {
        var data = Object.assign(
            {},
            this._stepOne.getData(),
            this._stepTwo.getData()
        );

        // ... do AJAX
    },

    render: function() {
        return (
            <StepOne ref={(ref) => this._stepOne = ref} />
            <StepTwo ref={(ref) => this._stepTwo = ref} />
        );
    }
});

这篇关于如何从React的子组件中获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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