我想有條件地渲染這樣的 React 組件:
parent.ts
...
<Parent>
<Child/>
<Parent>
...
child.ts
...
return (someBoolean && <Component/>)
...
我得到一個錯誤的打字原稿在child.ts那Its return type 'false | Element' is not a valid JSX element.
我希望條件在 中child.ts,因為它也用于其他地方,而不僅僅是parent.ts. 這樣做的合適方法是什么?我是否必須接受三元或 if/else?
uj5u.com熱心網友回復:
我想你輸了 { to evaluate }
return (<>
{someBoolean && <Component/>}
</>)
uj5u.com熱心網友回復:
根據我在 React 中使用數十萬個三元組的經驗,我建議使用它
const A = () => {
// Never in a form where it's easy to miss the ternary symbols
// Leads to bugs...
return (superUnderTip >= Math.pow(UserService.count(), 2)) ?
<ProviderTrainsFully lights={{hgih: 33}} rest={"too many null"} /> : null;
// Always in this form so your brain can super easily scan for the
// test and the output component.
return (superUnderTip >= Math.pow(UserService.count(), 2))
? <ProviderTrainsFully lights={{hgih: 33}} rest={"too many null"} />
: null;
// Never in a nested ternary -- make child components for additional
// conditional rendering.
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/354725.html
標籤:javascript 反应 打字稿
