ReactJs - Creating an “If” component… a good idea?

后端 未结 13 2327
南旧
南旧 2020-12-12 17:11

I\'ve read in the React docs that \"if\" type statements can\'t be used in JSX code, because of the way JSX renders into javascript, it doesn\'t work out as one would expect

13条回答
  •  死守一世寂寞
    2020-12-12 17:30

    I think it depends on the case. I just had the same question that why I'm here. I just think that if the component to render is huge, it can be usefull to have an IF component instead of the standard conditional rendering method.

    ...
    
           
    Then statement
    other Statement
    and so on
    ...

    is definitively more readable than

    ...
    {
      screenIs("xs") &&  (
         
             
    Then statement
    other Statement
    and so on
    ) } ...

    also for ternary statement,

    ...
    
       
           
    Then statement
    other then Statement
    and so on
    Else statement
    other Else Statement
    and so on
    ...

    is more readable than

    ...
    {
      screenIs("xs")
       ? (
         
             
    Then statement
    other Then Statement
    and so on
    ) : (
    Else statement
    other Else Statement
    and so on
    ) } ...

    anyway, to make it more readable, you can just define your conditional rendering part in some method and call it in your main render

    {
      ...
      renderParts = () => {
        return screenIs('xs') ? 
    XS
    :
    Not XS
    } ... render() { return ( ... {this.renderParts()} ... ) } }

提交回复
热议问题