Json ReactJS:如何调用父对象';从this.props.children中选择s setState()?
我有一个React路由器使用的父组件,其渲染功能类似于:Json ReactJS:如何调用父对象';从this.props.children中选择s setState()?,json,reactjs,Json,Reactjs,我有一个React路由器使用的父组件,其渲染功能类似于: render() { return ( <Grid> <Breadcrumb> {this.state.breadcrumbs} </Breadcrumb> {this.props.children}
render() {
return (
<Grid>
<Breadcrumb>
{this.state.breadcrumbs}
</Breadcrumb>
{this.props.children}
</Grid>
);
}
render(){
返回(
{this.state.breadcrumbs}
{this.props.children}
);
}
其中一个孩子将尝试获取()一些JSON。此json将包含一些额外的信息,我想更新父级的This.state.breadcrumbs
,但我不确定如何实现这一点。请尝试以下操作
父组件
updateState(newState){
this.setState({
breadcrumbs: newState,
})
}
render() {
var childrenwithProps = React.Children.map(this.props.children, function (child){
return React.cloneElement(child, {
updateParentState: this.updateState
})
})
return (
<Grid>
<Breadcrumb>
{this.state.breadcrumbs}
</Breadcrumb>
{childrenwithProps}
</Grid>
);
}
fetch()
.then()
.then(function(data){
this.props.updateParentState(data)
})
将更改父对象状态的函数作为道具传递给子对象。在子函数中,通过this.props.updateState
以新状态作为参数调用此函数。这将更新父级的状态
希望有帮助。性能方面。。。这慢吗?由于克隆元素通常看起来不太好…@Ben您没有选择权,因为要向this.props.children发送任何信息,您需要使用新的道具克隆它。就性能而言,我认为这不会产生太大影响。您可以做的一件好事是,通过在循环中检查只克隆必要的子项。这将减少对性能的影响。