【问题标题】:Conditonal Rendering of components [closed]组件的条件渲染[关闭]
【发布时间】:2020-10-05 23:26:44
【问题描述】:

我发现自己经常编写这样的代码,以避免使用深度嵌套的语句来确定返回值,例如:

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>
}

我对那个解决方案不是 100% 满意,(重复的代码,return 语句变得有些臃肿,而且很难查看 return 语句来了解发生了什么),我很担心它被认为是不好的风格。有没有更易读/更简洁的方法来做到这一点?

【问题讨论】:

    标签: reactjs coding-style


    【解决方案1】:

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

    Inline If with Logical && Operator

    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>
       );
    }
    

    【讨论】:

    • 是的,&lt;Warning&gt;&lt;/Warning&gt; 也可以是&lt;Warning /&gt;
    • 现在我一直在对字符串使用这种语法,但我从来没有想过我可以用整个组件/对象来做到这一点。
    • @xtr 不用担心,我们任何人随时都可能发生脑放屁。如果这是您要查找的内容,请接受答案,以便其他人知道它已解决。干杯。
    猜你喜欢
    • 2022-01-18
    • 2019-08-07
    • 1970-01-01
    • 1970-01-01
    • 2021-06-07
    • 2018-09-10
    • 1970-01-01
    • 1970-01-01
    • 2020-07-31
    相关资源
    最近更新 更多