【发布时间】:2017-04-17 22:01:26
【问题描述】:
父类有多个子组件,所有子组件都在 render 方法中实例化,因此父状态的任何更改都会导致所有子组件重新实例化,每次调用 render 时都会创建新的子组件实例,从而失去状态孩子,为了重用子实例,我尝试使用 parent.refs.childRef 检索子实例,但这给了我错误
未捕获的错误:对象作为 React 子级无效
,这是我的代码
placeHolderComponent(){
let component;
let palceHolderValue=this.state.uiState.placeHolder;
let classInstance=this;
if(palceHolderValue=='empty'){
component=<EmptyComponent></EmptyComponent>
}
else if(palceHolderValue=='search'){
component= classInstance.refs.gpSearchComponent!=null? classInstance.refs.gpSearchComponent: <GpSearch ref="gpSearchComponent"/>
}
return component;
}
这里 GpSearch 组件使用 ref 属性进行实例化,代码检查 parent.refs.childComponentRefId 是否不为空,然后渲染该实例,而不是一个新实例。我收到此错误
未捕获的错误:对象作为 React 子级无效(....如果您 意味着渲染一组孩子,使用数组代替或包装 使用 React 附加组件中的 createFragment(object) 的对象
【问题讨论】:
标签: reactjs