2 回答

TA貢獻(xiàn)1809條經(jīng)驗(yàn) 獲得超8個(gè)贊
如果一個(gè)組件有多個(gè)子代,this.props.children則將是一個(gè)數(shù)組。
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>
顯然,這僅適用于兩個(gè)孩子,但是您可以通過(guò)將整數(shù)傳遞給<HOC>props來(lái)告訴它選擇哪個(gè)孩子來(lái)擴(kuò)展它。
編輯
快速瀏覽文檔后,這是我上面編寫的更好的版本,因?yàn)閠his.props.children它不是數(shù)組,而是一個(gè)不透明的數(shù)據(jù)結(jié)構(gòu):
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貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超7個(gè)贊
我不確定我是否理解你。為什么需要將它設(shè)為HOC?
如果您將組件作為道具傳遞:
<HOC
componentOne={<ComponentOne />}
componentTwo={<ComponentTwo />}
/>
然后,您將可以使用道具訪問(wèn)它們。
render() {
return (
<div>
<button onClick={this.handleClick}>Click Me!</button>
{
this.state.onClick ?
this.props.componentOne :
this.props.componentTwo
}
</div>
);
}
添加回答
舉報(bào)