react显示隐藏的方法:1、通过state变量来控制是否渲染元素,类似vue中的【v-if】;2、通过style控制display属性,类似vue中的【v-show】;3、通过动态切换className。

react显示隐藏的方法: 方法一: 第一种方法是通过此例中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>
)
}
}要注意的是,这几种方法也有使用的区别: 相关免费学习推荐:JavaScript(视频)
以上就是react怎么显示隐藏的详细内容,更多请关注模板之家(www.mb5.com.cn)其它相关文章! |