React中返回的嵌套条件渲染

huangapple go评论60阅读模式
英文:

React nested conditional rendering in return

问题

我有以下的代码:

return (
  <Container>
    {param1 == false && param2 == false && (
      <CustomComponent>
      </CustomComponent>
    )}

    {param1 == false && param2 == true && (
      <CustomComponent2>
      </CustomComponent2>
    )}

    <Container>
    </Container>

  </Container>
);

目前的问题是&lt;Container&gt;组件在进行自定义组件检查后仍然被呈现,这是有道理的。

我希望只呈现一个组件(自定义、自定义2或只是容器),从这里的文档中 - https://react.dev/learn/conditional-rendering#conditionally-returning-jsx 我知道可以使用三元运算符来有条件地呈现组件,但我有3种情况要检查而不是2种。

现在我可以使用嵌套的三元运算符,但这不容易阅读,所以我想了解一种替代方法!

英文:

I have the following code

return (
  
  &lt;Container&gt;
    
    {param1==false &amp;&amp; param2==false &amp;&amp;(
      &lt;CustomComponent&gt; 
      &lt;/CustomComponent&gt;
      )}
      
    {param1 == false &amp;&amp; param2==true &amp;&amp;( 
      &lt;CustomComponent2&gt; 
      &lt;/CustomComponent2&gt;
      )}
      
    &lt;Container&gt;  
    &lt;/Container&gt;

  &lt;/Container&gt;
);

The problem right now is the &lt;Container&gt; component is still being rendered after the custom component checks have been made, which makes sense.

I want it so only 1 component is rendered ( either custom, custom2 or just the container ) from the docs here - https://react.dev/learn/conditional-rendering#conditionally-returning-jsx I know you can use ternary operator to conditionally render components but I have 3 cases to check not 2.

Now I could do nested ternary operators but that is not readable so I would like to know an alternative !

答案1

得分: 0

return (
<>
<Container>
{param1 == false && param2 == false ?
<CustomComponent>
</CustomComponent> :
param1 == false && param2 == true ?
<CustomComponent2>
</CustomComponent2> :
<Container>
</Container>
}
</Container>
</>
);

英文:
    you can check a multiple conditions in ternary operator
     like this
    
    return (
&lt;&gt;
     &lt;Container&gt;
        {param1==false &amp;&amp; param2==false ?
          &lt;CustomComponent&gt; 
          &lt;/CustomComponent&gt; :
           param1 == false &amp;&amp; param2==true ? 
           &lt;CustomComponent2&gt;     
           &lt;/CustomComponent2&gt; :
        &lt;Container&gt;  
        &lt;/Container&gt;
       }  
 &lt;/Container&gt;
&lt;/&gt;
);

huangapple
  • 本文由 发表于 2023年3月31日 23:07:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75900062.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定