关于react的条件渲染,这里列举四种方法,可以看哪种好用用哪种

class Movie extends React.Component{
  constructor(){
    super()
    this.state={
       isLogin:false
    }
  }
  render() {
    const {isLogin} = this.state
    return(
    
   )
  }
}
ReactDOM.render(
  <Movie/>,document.getElementById('app')
)

第一种,就是在render里面用if, else,适合逻辑代码非常多的情况

  render() {
    const {isLogin} = this.state
    let welcome = null
    if(isLogin){
      welcome = <h2>你好</h2>
    }else{
      welcome = <h2>不好</h2>
    }
    return(
      <div>
        {welcome}
        </div>
    )
  }
}

第二种就是用三元运算符

 <button>{isLogin?'为true':'为false'}</button>

第三种就是并运算符,为true,就显示后面的内容

{isLogin && <h2>{isLogin &&'你好啊'}</h2>}

第四种也是类似if,else

isLogin:true&& '你好' || '不好'

下面在演示下怎么实现vue里面的v-show效果,css的display:none

 <h2 style={{display:(isLogin?"block":"none")}}>v-show效果</h2>

其实感觉虽然比vue更复杂,但是感觉更灵活

Logo

前往低代码交流专区

更多推荐