if-else statement inside jsx: ReactJS

前端 未结 12 1162
广开言路
广开言路 2020-11-22 08:48

I need to change render function and run some sub render function when a specific state given,

For example:

render() {
    return (   
        

        
12条回答
  •  [愿得一人]
    2020-11-22 09:15

    As per DOC:

    if-else statements don't work inside JSX. This is because JSX is just syntactic sugar for function calls and object construction.

    Basic Rule:

    JSX is fundamentally syntactic sugar. After compilation, JSX expressions become regular JavaScript function calls and evaluate to JavaScript objects. We can embed any JavaScript expression in JSX by wrapping it in curly braces.

    But only expressions not statements, means directly we can not put any statement (if-else/switch/for) inside JSX.


    If you want to render the element conditionally then use ternary operator, like this:

    render() {
        return (   
            
                {this.state.value == 'news'? data: null }
            
        )
    }
    

    Another option is, call a function from jsx and put all the if-else logic inside that, like this:

    renderElement(){
       if(this.state.value == 'news')
          return data;
       return null;
    }
    
    render() {
        return (   
            
                { this.renderElement() }
            
        )
    }
    

提交回复
热议问题