react切换隐藏或显示状态(包含过渡动画)

Posted on 2020-10-11 00:47  猫头唔食鱼  阅读(1132)  评论(0编辑  收藏  举报

App.js

import React, { Component } from 'react';
import './style.css'
class App extends Component {
  constructor(props) {
    super(props);
    this.state = { 
      condition:true // 状态(隐藏或显示)
     }
  }
  // 切换隐藏或显示状态
  toggle=()=>{
    this.setState(()=>({
      condition:this.state.condition?false:true
    }))
   
  }
  render() { 
    return ( 
      <div>
        {/* 根据状态决定显示或隐藏的类名 */}
        <div className={this.state.condition?'show' :'hide'}>hello</div>
        <button onClick={this.toggle}>切换</button>
      </div>
     );
  }
}
 
export default App;

css

.show {
  opacity: 1;
  transition: all 1s;
}

.hide {
  opacity: 0;
  transition: all 1s;
}