一个元素之间的动画效果
github 找 react-transition-group
1.安装
yarn add react-transition-group
2.使用
<CSSTransition in={this.state.show} timeout={1000} classNames="fade" unmountOnExit onEntered={(el) => { el.style.color = 'blue' }} appear={true}>
<div>
hello
</div>
</CSSTransition>
// 1 unmountOnExit 隐藏之后会把 DOM 删除,设置unmountOnExit是否要在退出完成后卸载组件
//2 onEntered={(el) => { el.style.color = 'blue' }} 动画进入完成之后 ,变成蓝色
// el 指的是 <CSSTransition> </CSSTransition> 包裹的div元素
等价于
.fade-enter-done {
opacity: 1;
color: blue;
}
// 3 希望 hello 第一次展示的时候也有动画效果, 设置 appear={true}
.fade-enter,
.fade-appear {
opacity: 0;
}
.fade-enter-active,
.fade-appear-active {
opacity: 1;
transition: opacity 1s ease-in;
}
3.全部代码
image.png
App.js
import React, { Component, Fragment } from 'react';
import { CSSTransition } from 'react-transition-group';
import './style.css'
class App extends Component {
constructor(props) {
super(props);
this.state = {
show: true
}
this.handleToggole = this.handleToggole.bind(this)
}
render() {
return (
<Fragment>
<CSSTransition in={this.state.show} timeout={1000} classNames="fade" unmountOnExit onEntered={(el) => { el.style.color = 'blue' }} appear={true}>
<div>
hello
</div>
</CSSTransition>
<button onClick={this.handleToggole}>toggle</button>
</Fragment>
)
}
handleToggole() {
this.setState({
show: this.state.show ? false : true
})
}
}
export default App
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App'
ReactDOM.render(
// <React.StrictMode>
<App />,
// {/* </React.StrictMode>, */}
document.getElementById('root')
);
style.css
.fade-enter,
.fade-appear {
opacity: 0;
}
.fade-enter-active,
.fade-appear-active {
opacity: 1;
transition: opacity 1s ease-in;
}
.fade-enter-done {
opacity: 1;
color: red;
}
.fade-exit {
opacity: 1;
}
.fade-exit-active {
opacity: 0;
transition: opacity 1s ease-in;
}
.fade-exit-done {
opacity: 0;
}