反应事件层次问题

React event hierarchy issue

处理深度节点中也需要由父节点处理的状态更改的最佳方法是什么。这是我的情况:

<Table>
  <Row prop={user1}>
    <Column prop={user1_col1} />
    <Column prop={user1_col2} />
  </Row>
  <Row prop={user2}>
    <Column prop={user2_col1} />
    <Column prop={user2_col2} />
  </Row>
  <TableFooter>
    <FooterColumn prop={sum1} />
    <FooterColumn prop={sum2} />
  </TableFooter>
</Table>

每当有人更改列中的任何内容时 属性 我只需要在该列组件中维护该值的状态。但是,我现在想要 FooterColumn 组件中这些值的总和。实现此目标的最佳方法是什么?

如果我要传递状态更改,我必须在多个地方保留状态,然后传递它,这是一项非常繁琐的工作。最好使用 EventEmitter 还是我遗漏了什么?

所以,你只需要在父组件中跟踪状态,并与子组件共享状态更新功能:

var Parent = React.createClass({
  getInitialState: function() {
    return {
      users: [
        {name: 'Matt', values: [1, 2]},
        {name: 'user517153', values: [4, 5]}
      ]
    };
  },
  updateValue: function(rowId, colId, newValue) {
    var newUsersState = this.state;
    newUsersState.users[rowId].values[colId] = newValue;
    this.setState({users: newUsersState});
  },
  render: function() {
    var rows = this.state.users.map(function(user, r) {
      var cols = user.values.map(function(value, c) {
        return (
          <Column key={c} prop={value} rowId={r} colId={c} onChange={this.updateValue}/>
        );
      });

      return (
        <Row key={r} prop={user}>
          {cols}
        </Row>
      );
    });

    // Yes, it could be more efficient if you did it all in one map/forEach - doing this in a second one for clarity
    var footerCols = this.state.users.map(function(user) {
      var sum = 0;
      user.values.forEach(function(value) { sum+= value; });
      return (
        <FooterColumn prop={sum} />
      );
    });

    return (
      <Table>
        {rows}
        <TableFooter>
          {footerCols}
        </TableFooter>
      </Table>
    );
  }
});

在您的 Column class 中,您只需要以下内容:

var Column = React.createClass({
  onChange: function(event) {
    var props = this.props;

    var newValue = event.target.value; // Get the new value somehow - this is just an example
    props.onChange(props.rowId, props.coldId, newValue);
  },
  render: function() {
    var props = this.props;

    return (
      <td onChange={this.onChnage}>{props.prop}</td>
    );
  }
});

希望这是有道理的。