[英]Conditional rendering from a functional component
我想有條件地渲染這樣的 React 組件:
parent.ts
...
<Parent>
<Child/>
<Parent>
...
child.ts
...
return (someBoolean && <Component/>)
...
我在child.ts
中收到一個 TypeScript 錯誤, Its return type 'false | Element' is not a valid JSX element.
Its return type 'false | Element' is not a valid JSX element.
我希望條件在child.ts
,因為它也用於其他地方,而不僅僅是parent.ts
。 這樣做的合適方法是什么? 我是否必須接受三元或 if/else?
我想你輸了{ to evaluate }
return (<>
{someBoolean && <Component/>}
</>)
根據我在 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.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.