2016-05-15 127 views
0

的标题可能会更清晰,但这真的是我能想到的最好的,对不起。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次。

奇怪而不可思议。我在这里做错了什么?

+2

代码看起来不错,你可以发布一个错误可以被重现的例子吗? – damio

+0

难道你不能只是'this.prop.children.map(...)'?也许这也是''没有'钥匙'的问题?虽然我也不能确定你的代码中的明显错误...... – Scarysize

回答

0

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

FWIW,我被附接至onChangethis.handleChange下拉列表中Filter成分的ComponentDidMountComponentDidUpdate。从ComponentDidUpdate删除初始化,解决了这个问题。这是因为每次更新组件时都会将handleChange的多个实例绑定到onChange事件。