问题描述
我正在尝试为条件渲染创建一个 switch HOC,它的行为类似于 ReactTS 中的 switch 语句
<Switch>
<Case condition={cond1}>
Hello
</Case>
<Case condition={cond2}>
World
</Case>
<Default>
Hi stranger
</Default>
</Switch>
如果 cond1 为真,则渲染“Hello”。
如果 cond1 为假但 cond2 为真,则渲染“世界”。
如果这两个条件都为假,则呈现“嗨陌生人”。
解决方法
我在 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;
}
默认.js
export default function(props) {
return props.children;
}
使用上述文件作为
<Switch>
<Case condition={false}>Hello</Case>
<Case condition={false}>World</Case>
<Default>Hi</Default>
</Switch>