标题可能更清晰,但这确实是我能想到的最好的,对不起。
因此,我试图在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
}
});
然后,我创建了一个表组件:
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'));
它渲染得很好。变更功能似乎也很好。然而,我发现每次更改filter值时,它都会触发Table的filterChanged方法,次数会增加。第一次更改,将触发2次;第二次变化,6次;第三次更改,14次。
怪异而离奇。我在这里做错了什么?
就React而言,上面的操作过程是正确的。我遇到的错误是由于另一个框架(Materialize)使用jquery插件来初始化一些组件。由于它改变了DOM,我需要手动确保onChange事件正确地附加到正确的节点。
Fwiw,我在Filter
组件的ComponentDidMount
和ComponentDidUpdate
的下拉列表中将onChange
附加到this.handleChange
。从ComponentDidUpdate
中删除初始化,解决了问题。这是因为每次组件更新时,handleChange
的多个实例都绑定到onChange
事件。