gpt4 book ai didi

javascript - 不使用三元运算符条件渲染 React 组件

转载 作者:行者123 更新时间:2023-12-05 02:38:02 26 4
gpt4 key购买 nike

您好,目前有以下代码 React 代码:

  return (
<Container>
{booleanValueOne ? (
<TrueComponent props={props} />
) : (
[
<DefaultComponentOne props={props} />,
<DefaultComponentTwo props={props} />,
]
)}
</Container>
);

所以如果booleanValueOne是真的我们返回<TrueComponent如果不返回 DefaultComponents 数组。这很简单。

但我想添加第二个 bool 值:booleanValueTwo - 如果是,返回 TrueComponentTwo & 如果 booleanValueOne 都不是或 booleanValueTwo为真,返回默认组件数组。

任何人都可以分享这样做的最佳做法吗?

我不能使用三元组,因为我有 3 种可能的结果。

最佳答案

你可以有嵌套的三元组。如果正确对齐应该是可读的

const result = booleanValueOne ? (
<TrueComponent props={props} />
) : booleanValueTwo ? (
<TrueComponentTwo props={props} />
) : (
[<DefaultComponentOne props={props} />, <DefaultComponentTwo props={props} />]
);


return (<Container>{result}</Container>)

或者您可以使用正常的控制流 if - else if 将正确的值分配给 result 变量。

let result = null;

if (booleanValueOne) {
result = <TrueComponent props={props} />;
} else if (booleanValueTwo) {
result = <TrueComponentTwo props={props} />;
} else {
result = [
<DefaultComponentOne props={props} />,
<DefaultComponentTwo props={props} />,
];
}

关于javascript - 不使用三元运算符条件渲染 React 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69808906/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com