2 回答

TA贡献1809条经验 获得超8个赞
如果一个组件有多个子代,this.props.children则将是一个数组。
class HOC extends React.Component {
// ... rest of code ....
render() {
const { onClick } = this.state;
const { children } = this.props;
return !onClick ? children[0] : children[1];
}
}
然后像这样使用它:
<HOC>
<div>Child One</div>
<div>Child Two</div>
</HOC>
显然,这仅适用于两个孩子,但是您可以通过将整数传递给<HOC>props来告诉它选择哪个孩子来扩展它。
编辑
快速浏览文档后,这是我上面编写的更好的版本,因为this.props.children它不是数组,而是一个不透明的数据结构:
class HOC extends React.Component {
// ... rest of code ...
render() {
const { onClick } = this.state;
const children = React.Children.toArray(this.props.children);
return !onClick ? children[0] : children[1];
}
}

TA贡献1818条经验 获得超7个赞
我不确定我是否理解你。为什么需要将它设为HOC?
如果您将组件作为道具传递:
<HOC
componentOne={<ComponentOne />}
componentTwo={<ComponentTwo />}
/>
然后,您将可以使用道具访问它们。
render() {
return (
<div>
<button onClick={this.handleClick}>Click Me!</button>
{
this.state.onClick ?
this.props.componentOne :
this.props.componentTwo
}
</div>
);
}
添加回答
举报