react中控制元素的显示与隐藏

1.通过 state 变量来控制是否渲染元素

类似于 vuev-if

方法是通过变量来控制是否加载元素的,如果变量为false,内容就直接不会渲染的。

class Demo extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            isShow:true
        }
    }
    render(){
        return (
            <div>
                {
                    this.state.isShow?(
                        <div>显示的元素</div>
                    ):null
                }
            </div>
        )
    }
}
2.通过 style控制 display 属性

类似于 vue 中的 v-show

通过 display 属性来控制元素显示与隐藏

class Demo extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            isShow:'none'
        }
    }
    render(){
        return (
            <div style={{display:this.state.isShow}}>显示的元素</div>
        )
    }
}
3.通过动态切换className

通过className切换类名来实现元素的显示和隐藏。

//.css文件
.is-show{
    display:none
}
//.js文件
class Demo extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            isShow:true
        }
    }
    render(){
        return (
            <div>
              // 写法一 
              <div className={this.state.isShow?'old':'old is-show'}>显示的元素</div>
              // 写法二
              <div className={`${this.state.isShow?'':'is-show'} old`}>显示的元素</div>
            </div>
        )
    }
}

第一种方法不适合频繁控制显示隐藏的情况,因为它会重新渲染元素,比较耗费性能。



posted on 2020-05-21 13:36  ranyonsue  阅读(9579)  评论(0编辑  收藏  举报

导航