Home > Web Front-end > JS Tutorial > How to control display and hide in react

How to control display and hide in react

coldplay.xixi
Release: 2021-01-08 17:23:09
Original
7846 people have browsed it

Methods for controlling display and hiding in react: 1. Control whether to render elements through state variables; 2. Control the display attribute through style; 3. Dynamically switch className.

How to control display and hide in react

The operating environment of this tutorial: windows7 system, React17 version, Dell G3 computer.

Methods for controlling display and hiding in react:

1. Use state variables to control whether to render elements

Similar to vue'sv The -if

method uses variables to control whether to load elements. If the variable is false, the content will not be rendered directly.

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

2. Control the display attribute through style

Similar to v-show in vue

Control the display and hiding of elements through the display attribute

class Demo extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            isShow:&#39;none&#39;
        }
    }
    render(){
        return (
            <div style={{display:this.state.isShow}}>显示的元素</div>
        )
    }
}
Copy after login

3. By dynamically switching className

Switch the class name through className to display and hide elements.

//.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?&#39;old&#39;:&#39;old is-show&#39;}>显示的元素</div>
              // 写法二
              <div className={`${this.state.isShow?&#39;&#39;:&#39;is-show&#39;} old`}>显示的元素</div>
            </div>
        )
    }
}
Copy after login

Related free learning recommendations: javascript (video)

The above is the detailed content of How to control display and hide in react. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template