[英]Setting a prop of a child component inside a parent component in ReactJS
我正在创建一个分页表,并且希望能够自定义行输出。
看起来像。
var PagedTable = React.createClass({
propTypes:{
'table_headers' : React.PropTypes.array,
'table_rows' : React.PropTypes.array
},
getInitialState: function(){
return{
pageSize: 10,
currentPage: 1
}
},
componentWillReceiveProps: function(nextProps) {
this.setState({
currentPage: 1
})
},
getPage: function(){
var start = this.state.pageSize * (this.state.currentPage - 1);
var end = start + this.state.pageSize;
return{
currentPage: this.state.currentPage,
table_rows: this.props.table_rows.slice(start, end),
numPages: this.getNumPages(),
handleClick: function(pageNum) {
return function() {
this.handlePageChange(pageNum)
}.bind(this)
}.bind(this)
}
},
getNumPages: function() {
var numPages = Math.floor(this.props.table_rows.length / this.state.pageSize);
if (this.props.table_rows.length % this.state.pageSize > 0){
numPages++
}
return numPages
},
handlePageChange: function(pageNum) {
this.setState({currentPage: pageNum})
},
render:function(){
var page = this.getPage();
var topics = page.table_rows.map(function(row) {
return <IncompleteRow row={row}/>
});
return <div>
<table className="table table-hover table-primary table-bordered colm-freeze">
<PagedRowHeader header_row={this.props.table_headers}/>
{topics}
</table>
</div>
}
});
上面的代码已修改,但高度基于: this 。
<PagedTable>
<IncompleteRow/>
</PagedTable>
或喜欢
<PagedTable>
<CompletedRow/>
</PagedTable>
如你看到的。 现在,我在render方法中设置了不完整的行。 但我想使此组件可扩展。 这意味着我希望能够呈现不同种类的行。
问题在于要知道要呈现哪些行,我需要进入PagedTable类,因为它知道当前应显示哪些行。 因此,我的PagedTable需要知道它要呈现哪种类型的行。
我已经尝试过使用this.props.children,但是我对如何从父组件设置孩子的proptype感到困惑。
也许我对您要完成的工作感到困惑,但是您不能做类似的事情:
var topics = page.table_rows.map(function(row) {
return row.someFlag ? <CompletedRow row={row}/> : <IncompleteRow row={row}/>;
});
我陷入了如何从父组件设置孩子的原型的问题。
我使用React.Children和React.cloneElement来映射具有父类正确属性的子元素。
React.Children.map(this.props.children, function (child) {
return React.cloneElement(child, {
someProperty: this.props.someProperty
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.