【问题标题】:ReactJs aggregate data from componentsReactJs 聚合来自组件的数据
【发布时间】:2015-02-18 20:44:42
【问题描述】:

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

【问题讨论】:

    标签: javascript reactjs react-jsx reactjs-flux


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多