【发布时间】: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(...)吗?也许这也是<Filter />s 没有key的问题?虽然我也无法确定您的代码中有明显的错误......
标签: javascript reactjs children