模拟vue中的v-if
class Test { state = { bool: true } toggle = () => { this.setState({ bool: !this.state.bool }) } render () { return ( <> // 双与运算符 短路效果 {bool && <div>bool为true时显示,为false时隐藏</div>} // 三元表达式 {bool ? <div>bool为true时显示,为false时隐藏</div> : ''} <button onClick={this.toggle}>toggle</button> </> ) }}
模拟vue中的v-show
class Test { state = { display: 'block' } toggle = () => { this.setState({ display: this.state.display === 'block' ? 'none' : 'block' }) } render () { const { display } = this.state; return <> <div style={{ display }}>bool为true时显示,为false时隐藏</div> <button onClick={this.toggle}>toggle</button> </> }}