ReactJs聚合来自组件的数据

时间:2014-12-19 21:24:43

标签: javascript reactjs react-jsx reactjs-flux

将大组件拆分成多个较小组件并汇总其数据的最佳方法是什么?我想访问FormComponent中BillingDataComponent,NameComponent和AddressComponent的状态。

示例:

var FormComponent = React.createClass({
  _onClick: function() {
    // Access child data here
    var name = ???
    var address = ???
    var billingData = ???

    ActionCreator.updateFormDataOnServer(formDataAggregatedFromChildren);
  },

  render: function() {
    return (
      <div>
        <form>
          <NameComponent name="Maybe the name is already set?" />
          <AddressComponent />
          <BillingDataComponent />
          <button onClick={this._onClick} >Submit</button>
        </form>
      <div>
    );
  }
});

var NameComponent = React.createClass({  
  _onChange: function(e) {
    this.setState({
      value: e.target.value
    });
  },

  render: function() {
    return (
      <div>
        <input type="text" value={this.state.value} onChange={this._onChange} />
      </div>
    );
  }
});

// AddressComponent and BillingDataComponent similiar

1 个答案:

答案 0 :(得分:2)

您应该让FormComponent拥有数据并将其作为道具传递给其他组件。当数据发生变化时,孩子们应该将更改传播到以下格式:

var FormComponent = React.createClass({
  getInitialState: function() {
    return {
      name: ""
    };
  },

  _onClick: function() {
    // Access child data here
    var name = ???
    var address = ???
    var billingData = ???

    ActionCreator.updateFormDataOnServer(formDataAggregatedFromChildren);
  },

  _onNameChange: function(name) {
    this.setState({
      name: name
    });
  },

  render: function() {
    return (
      <div>
        <form>
          <NameComponent onChange={this._onNameChange} value={this.state.name} />
          <AddressComponent />
          <BillingDataComponent />
          <button onClick={this._onClick} >Submit</button>
        </form>
      <div>
    );
  }
});

var NameComponent = React.createClass({  
  _onChange: function(e) {
    this.props.onChange(e.target.value);
  },

  render: function() {
    return (
      <div>
        <input type="text" value={this.props.value} onChange={this._onChange} />
      </div>
    );
  }
});

// AddressComponent and BillingDataComponent similiar