英文:
React nested conditional rendering in return
问题
我有以下的代码:
return (
  <Container>
    {param1 == false && param2 == false && (
      <CustomComponent>
      </CustomComponent>
    )}
    {param1 == false && param2 == true && (
      <CustomComponent2>
      </CustomComponent2>
    )}
    <Container>
    </Container>
  </Container>
);
目前的问题是<Container>组件在进行自定义组件检查后仍然被呈现,这是有道理的。
我希望只呈现一个组件(自定义、自定义2或只是容器),从这里的文档中 - https://react.dev/learn/conditional-rendering#conditionally-returning-jsx 我知道可以使用三元运算符来有条件地呈现组件,但我有3种情况要检查而不是2种。
现在我可以使用嵌套的三元运算符,但这不容易阅读,所以我想了解一种替代方法!
英文:
I have the following code
return (
  
  <Container>
    
    {param1==false && param2==false &&(
      <CustomComponent> 
      </CustomComponent>
      )}
      
    {param1 == false && param2==true &&( 
      <CustomComponent2> 
      </CustomComponent2>
      )}
      
    <Container>  
    </Container>
  </Container>
);
The problem right now is the <Container> 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 (
<>
     <Container>
        {param1==false && param2==false ?
          <CustomComponent> 
          </CustomComponent> :
           param1 == false && param2==true ? 
           <CustomComponent2>     
           </CustomComponent2> :
        <Container>  
        </Container>
       }  
 </Container>
</>
);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论