模拟vue中的v-if

  1. class Test {
  2. state = {
  3. bool: true
  4. }
  5. toggle = () => {
  6. this.setState({
  7. bool: !this.state.bool
  8. })
  9. }
  10. render () {
  11. return (
  12. <>
  13. // 双与运算符 短路效果
  14. {bool && <div>booltrue时显示,为false时隐藏</div>}
  15. // 三元表达式
  16. {bool ? <div>booltrue时显示,为false时隐藏</div> : ''}
  17. <button onClick={this.toggle}>toggle</button>
  18. </>
  19. )
  20. }
  21. }

模拟vue中的v-show

  1. class Test {
  2. state = {
  3. display: 'block'
  4. }
  5. toggle = () => {
  6. this.setState({
  7. display: this.state.display === 'block' ? 'none' : 'block'
  8. })
  9. }
  10. render () {
  11. const { display } = this.state;
  12. return <>
  13. <div style={{ display }}>booltrue时显示,为false时隐藏</div>
  14. <button onClick={this.toggle}>toggle</button>
  15. </>
  16. }
  17. }