的標題可能會更清晰,但這真的是我能想到的最好的,對不起。React在外部渲染render()
所以,我試圖在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'));
呈現很好。更改功能似乎也沒有問題。但是,我發現每次更改過濾器值時,都會觸發Table的filterChanged方法,從而增加次數。首先改變,它會觸發2次;第二次改變,6次;第三次改變,14次。
奇怪而不可思議。我在這裏做錯了什麼?
代碼看起來不錯,你可以發佈一個錯誤可以被重現的例子嗎? – damio
難道你不能只是'this.prop.children.map(...)'?也許這也是' '沒有'鑰匙'的問題?雖然我也不能確定你的代碼中的明顯錯誤...... –
Scarysize