if-else statement inside jsx: ReactJS

前端 未结 12 1226
广开言路
广开言路 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:17

    You can achieve what you are saying by using Immediately Invoked Function Expression (IIFE)

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

    Here is the working example:

    But, In your case, you can stick with the ternary operator

提交回复
热议问题