JavaScript/react/元素显示隐藏

来自康健生活
Kangkk​(留言 | 贡献)2021年2月20日 (六) 03:00的版本 (创建页面,内容为“== 标题文字 == 第一种方法是通过此例中showElem变量来控制是否加载元素的,如果showElem为false,内容是直接不会渲染的。 <syntax…”)
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)

标题文字

第一种方法是通过此例中showElem变量来控制是否加载元素的,如果showElem为false,内容是直接不会渲染的。

class Demo extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            showElem:true
        }
    }
    render(){
        return (
            <div>
                {
                    this.state.showElem?(
                        <div>显示的元素</div>
                    ):null
                }
            </div>
        )
    }
}

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

class Demo extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            showElem:'none'
        }
    }
    render(){
        return (
            <div style={{display:this.state.showElem}}>显示的元素</div>
        )
    }
}

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

class Demo extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            showElem:true
        }
    }
    render(){
        return (
            <div>
                {/* 写法一 */}
                <div className={this.state.showElem?'word-style':'word-style hide'}>显示的元素</div>
                {/* 写法二 */}
                <div className={`${this.state.showElem?'':'hide'} word-style`}>显示的元素</div>
            </div>
        )
    }
}