Home >Web Front-end >Front-end Q&A >How to hide elements based on conditions in react
Implementation method: 1. Use the state variable to control whether to render the element. If the value is false, the content will not be rendered directly; 2. Control the display attribute through style, and hide the element when the attribute value is none; 3. Dynamically switch hide through className to display and hide elements.
#The operating environment of this tutorial: Windows7 system, react18 version, Dell G3 computer.
React
There are three ways to control the display and hiding of elements:
The first is through the state
variable Control whether to render elements, similar to v-if
in vue
.
The second is to control the display
attribute through style
, similar to v-show in
vue
.
The third method is to dynamically switch className
.
The first method is to use the showElem variable in this example to control whether to load the element. If showElem is
false
, the content will not be rendered directly.
class Demo extends React.Component{ constructor(props){ super(props); this.state = { showElem:true } } render(){ return ( <div> { this.state.showElem?( <div>显示的元素</div> ):null } </div> ) } }
This method is very simple, it is to control the display and hiding of elements through the display
attribute.
class Demo extends React.Component{ constructor(props){ super(props); this.state = { showElem:'none' } } render(){ return ( <div style={{display:this.state.showElem}}>显示的元素</div> ) } }
Switch hide
through className
to realize the display and display of elements 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> ) } }
Method 1 is not suitable for frequent control of display and hiding, because it will re-render elements, which is more performance-intensive. In this case, the second or third method is more reasonable to control through display.
Method 1 is suitable for pages with high security, such as user information pages. Different content is displayed according to different user levels. At this time, if you use method 1 or 2, users can still see it if they open the network. , because the page is still rendered, just hidden. The first method is to directly not render the DOM elements of user information, ensuring security.
【Related recommendations: Redis video tutorial, Programming teaching】
The above is the detailed content of How to hide elements based on conditions in react. For more information, please follow other related articles on the PHP Chinese website!