React display and hide methods: 1. Use state variables to control whether to render elements, similar to [v-if] in vue; 2. Control the display attribute through style, similar to [v-show] in vue ;3. By dynamically switching className.
The operating environment of this tutorial: windows10 system, react16, this article is applicable to all brands of computers.
react display hidden method:
Method one:
The first method is through ## in this example #showElemVariable to control whether to load elements. 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> ) } }
Method 2:
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> ) } }
Method 3:
Switch hide through className to display and hide elements.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> ) } }
Related free learning recommendations: JavaScript(Video)
The above is the detailed content of How to show and hide in react. For more information, please follow other related articles on the PHP Chinese website!