【问题标题】:React adding child outside render()反应在渲染()之外添加孩子
【发布时间】:2016-05-15 07:12:40
【问题描述】:

标题可能更清楚,但这确实是我能想到的最好的,抱歉。

所以,我正在尝试在 React 中创建一个过滤表组件。但是,我希望过滤器的定义独立于表本身的定义。所以,这就是我正在做的事情。

我创建了一个过滤器组件:

var Filter = React.createClass({
  handleChange : function (value) {
    this.props.updateTable(this.props.columnName,value);
  },
  render : function () {
    //an input that will report its value to this.handleChange
  }
});

然后,我创建一个 Table 组件:

var Table = React.createClass({
  filterChanged : function (column, value) {
    //this will be wired as a updateTable prop for the Filter
  },
  render : function () {
    //I am trying not to define a filter here,
    //I am trying to use the previously-defined Filter component.
    //I want the Table component to remain generic and re-usable,
    //with  optional filters.
    var thisComponent = this;
    //I can have as many filters as I want.
    var filterToRender = React.Children.map(this.props.children, function (child) {
      var filterUI;
      if (child.type.displayName === 'Filter') {
        filterUI = React.cloneElement(child, {updateTable : thisComponent.filterChanged});
      }
      return (<div>{filterUI}</div>);
    });
    //along with the rest of the table UI,
    return (<div>
      <table>bla bla</table>
      {filterToRender}
    </div>);
  }
});

然后,在我的主页中,我将它呈现如下:

ReactDOM.render( (<Table>
  <Filter columnName='status'></Filter>
</Table>), document.getElementById('appHolder'));

它渲染得很好。更改功能似乎也很好。但是,我发现每次更改过滤器值时,都会触发Table的filterChanged方法,次数增加。第一次更改,会触发2次;第二次变化,6次;第 3 次更改,14 次。

奇怪而离奇。我在这里做错了什么?

【问题讨论】:

  • 代码看起来不错,你能发布一个可以重现错误的例子吗?
  • 你不应该只是this.prop.children.map(...) 吗?也许这也是&lt;Filter /&gt;s 没有key 的问题?虽然我也无法确定您的代码中有明显的错误......

标签: javascript reactjs children


【解决方案1】:

就 React 而言,上述做事的过程是正确的。我得到的错误是由于另一个框架(Materialize)使用 jquery 插件来初始化一些组件。由于它会改变 DOM,我需要手动确保 onChange 事件正确附加到正确的节点。

Fwiw,我在Filter 组件的ComponentDidMount ComponentDidUpdate 的下拉列表中将onChange 附加到this.handleChange。从ComponentDidUpdate 中删除初始化,解决了这个问题。这是因为每次更新组件时都会将多个handleChange 实例绑定到onChange 事件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-17
    • 1970-01-01
    • 2018-12-22
    • 1970-01-01
    • 2014-12-03
    • 2019-06-10
    • 2017-08-28
    相关资源
    最近更新 更多