[英]Conditional rendering from a functional component
I'd like to conditionally render a React component like this:我想有条件地渲染这样的 React 组件:
parent.ts
...
<Parent>
<Child/>
<Parent>
...
child.ts
...
return (someBoolean && <Component/>)
...
I get a TypeScript error in child.ts
that Its return type 'false | Element' is not a valid JSX element.
我在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.
I want the conditional to be in child.ts
, because it is used in other places as well, not just parent.ts
.我希望条件在child.ts
,因为它也用于其他地方,而不仅仅是parent.ts
。 What's the appropriate way to do this?这样做的合适方法是什么? Would I have to settle for a ternary or if/else?我是否必须接受三元或 if/else?
i think you lost { to evaluate }
我想你输了{ to evaluate }
return (<>
{someBoolean && <Component/>}
</>)
In my experience using hundreds of thousands of ternaries in React, I would recommend using it like根据我在 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.