Use if statement in React JSX

前端 未结 3 1273
你的背包
你的背包 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 12:57

    Better to use with ternary Operator, By doing so you can also add else block to your code.

    Try this:

    var chartGraphContent =
            
    {this.state.modalityGraph['nca'] > 0 ?
    : "Else Block" }
    ;

    Update (Another method)

    and in case for more complex and large condition you can call inline functions too to return your template , in this way you can avoid your code to become messy. here is an example.

    var ifBlockCode = function ifBlockCode(){
        return (
            
    ) } var elseBlockCode = function elseBlockCode(){ return ( Else Block ) } var chartGraphContent =
    {this.state.modalityGraph['nca'] > 0 ? {this.ifBlockCode} : {this.elseBlockCode} }
    ;

提交回复
热议问题