- '?' 符号三目运算
{ this.state.isShow ? <h2>既然是要成为一名正真的爱坤,那么请大声地喊出我们的爱坤口号!</h2>:null }
- ‘&&’与符号判断
{ this.state.isShow && <h2>我们的口号是唱跳rap篮球!</h2> }
- 通过className或者style的css属性的display进行隐藏与显示
constructor(props){
super(props)
this.state={
isShow:true,
H2style:{display: 'none'}
}
}
<h2 style={this.state.isShow ? null:this.state.H2style}>小黑子终于漏出鸡脚了吧</h2>
- 另外您也可以使用dangerouslySetInnerHTML进行富文本插入来进行显示与隐藏,注意:富文本插入极度危险
<h2 dangerouslySetInnerHTML={ {__html: this.state.isShow ? '正真的爱坤没有口号,真正的爱坤都是爱在心里的':null} }></h2>
代码示例:
import React, { Component } from 'react'
export default class App extends Component {
constructor(props){
super(props)
this.state={
isShow:true,
H2style:{display: 'none'}
}
}
render() {
return (
<div>
<button onClick={()=>{this.ikunFun()}}>点击</button>
{ this.state.isShow ? <h2>既然是要成为一名正真的爱坤,那么请大声地喊出我们的爱坤口号!</h2>:null }
{ this.state.isShow && <h2>我们的口号是唱跳rap篮球!</h2> }
<h2 style={this.state.isShow ? null:this.state.H2style}>小黑子终于漏出鸡脚了吧</h2>
<h2 dangerouslySetInnerHTML={ {__html: this.state.isShow ? '正真的爱坤没有口号,真正的爱坤都是爱在心里的':null} }></h2>
</div>
)
}
ikunFun(){
this.setState({
isShow:!this.state.isShow
})
}
}