首页 > 解决方案 > Conditonal Rendering of components

问题描述

I find myself writing code like this quite frequently, to avoid deeply nested statements to determine return values e.g.:

function Warning(props){
   return <h1> Warning! </h1>
}
 
function SomeComponent(props){
   const [showAtTop, setShowAtTop] = useState(false); 
    
   //...

   const ShowWarningAtTop = showAtTop
      ? <Warning></Warning>
      : null
   const ShowAtBottom = showAtTop
      ? null
      : <Warning></Warning>


   return <div>
      {showWarningAtTop}
      <div> Main Content</div>
      {showWarningAtBottom}
   </div>
}

I'm not 100% satisfied with that solution, (repetetive code, return statement gets somewhat bloated and it's quite hard to look at the return statement to see whats happening) and i'm anxious that it's considered bad style. Is there a more readable / cleaner way to do this?

标签: reactjscoding-style

解决方案


使用逻辑 AND ( &&) 的更短/更简单的条件渲染。

内联 If 与逻辑 && 运算符

React 忽略输出中的布尔值。只有 react 组件需要返回null以表明它们没有渲染任何内容,组件的任何内容都可以返回 true/false,并且 react 将忽略并且不渲染文字值。

你也可以在 JSX 中自动关闭空标签。

function SomeComponent(props){
   const [showAtTop, setShowAtTop] = useState(false); 
    
   //...

   return (
     <div>
       {showAtTop && <Warning />}
       <div> Main Content</div>
       {showAtTop && <Warning />}
     </div>
   );
}

推荐阅读