React控制元素顯示和隱藏的方法目前我知道的有三種方法:
第一種是通過state變量來控制是否渲染元素,類似vue中的v-if。
第二種是通過style控制display屬性,類似vue 中的v-show。
第三種是通過動態切換className。
第一種方法是通過此例中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>
)
}
}
方法2 這個方法很簡單,就是通過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>
)
}
}
方法一不適合頻繁控制顯示隱藏的情況,因為他會重新渲染元素,比較耗費性能。在這種情況下,第二種或者第三種通過display來控制會更合理。
方法一適合安全性高的頁面,比如用戶信息頁面,根據不同的用戶級別顯示不一樣的內容,這時候如果你用方法一或者方法二的話,用戶如果打開network還是可以看見,因為頁面還是渲染了,只是隱藏了而已。而方法一是直接不渲染用戶信息的DOM元素,保證了安全性。
