嗨,目前有以下代碼 React 代碼:
return (
<Container>
{booleanValueOne ? (
<TrueComponent props={props} />
) : (
[
<DefaultComponentOne props={props} />,
<DefaultComponentTwo props={props} />,
]
)}
</Container>
);
所以如果booleanValueOne是真的我們回傳<TrueComponent,如果不是回傳一個 DefaultComponents 陣列。這很簡單。
但我既然要添加第二個布林值:booleanValueTwo-如果這是真的,回報TrueComponentTwo及如果沒有的booleanValueOne或者booleanValueTwo是真實的,回傳默認組件的陣列。
任何人都可以分享這樣做的最佳實踐嗎?
我不能使用三元,因為我有 3 種可能的結果。
uj5u.com熱心網友回復:
你可以有嵌套的三元組。如果正確對齊應該是可讀的
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} />,
];
}
uj5u.com熱心網友回復:
您可以使用此模板:
return (
<Container>
{booleanValueOne && (
<TrueComponent props={props} />
)}
{(!booleanValueOne && booleanValueTwo) && (
<TrueComponentTwo props={props} />
)}
{(!booleanValueOne && !booleanValueTwo) && (
[
<DefaultComponentOne props={props} />,
<DefaultComponentTwo props={props} />,
]
)}
</Container>
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/344929.html
標籤:javascript 反应
上一篇:如何將物件映射到ui?
