Use if statement in React JSX

前端 未结 3 1282
你的背包
你的背包 2020-11-29 12:17

Can you use a if statement in JSX like this?

    var chartGraphContent =
        
if(this.state.modalityG
3条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 13:08

    Use conditional rendering, and since you have no else-case, you can use && instead of a ternary operator for brevity:

    It works because in JavaScript, true && expression always evaluates to expression, and false && expression always evaluates to false.

    Therefore, if the condition is true, the element right after && will appear in the output. If it is false, React will ignore and skip it.

    Thus:

       
    {this.state.modalityGraph['nca'] > 0 &&
    }

    This will only render JSX if a condition is true. If it is false, React won't render anything. Remember, you have to wrap inline JavaScript expressions in JSX with { … }, you can't just have it inside JSX.

    Using if/else statements directly is JSX will cause it to be rendered literally as text, which isn't desired. You also can't use them in inline JavaScript expressions because if statements are not expressions, so this won't work:

    {
      if(x) y
    }
    

提交回复
热议问题