繁体   English   中英

来自功能组件的条件渲染

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM