根据条件呈现其中一个子元素



我正在尝试为条件渲染创建一个开关HOC,其行为类似于ReactTS中的开关语句

<Switch>
<Case condition={cond1}>
Hello
</Case>
<Case condition={cond2}>
World
</Case>
<Default>
Hi stranger
</Default>
</Switch>

如果条件为真,则显示&;hello &;。
如果cond1为假,但cond2为真,则呈现&;world &;。
如果两个条件都为假,则显示"Hi stranger">

我在JS中创建了三个文件一次进行测试,一切正常。

Switch.js

class Switch extends React.Component {
getComponentToRender() {
return React.Children.toArray(this.props.children).find(function (child) {
if (child.type.name === "Case") {
if (child.props.condition) {
return true;
}
}
if (child.type.name === "Default") {
return true;
}
return false;
});
}
render() {
return this.getComponentToRender();
}
}
export default Switch;

Case.js→需要确保该组件的条件为布尔值。

export default function(props) {
return props.children;
}

Default.js

export default function(props) {
return props.children;
}

使用以上文件作为

<Switch>
<Case condition={false}>Hello</Case>
<Case condition={false}>World</Case>
<Default>Hi</Default>
</Switch>

相关内容

最新更新