ReactJs 聚合来自组件的数据

ReactJs aggregate data from components

本文关键字:组件 数据 ReactJs      更新时间:2023-09-26

将一个大组件拆分为多个较小的组件并聚合其数据的最佳方法是什么?我想在 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

你应该让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