React过渡动画组件基础使用介绍

 

1. 基础使用

介绍:

在项目中可能会给一些组件的显示或隐藏添加某种过渡动画,这样可以很好的增加用户的使用体验, react-transition-group 是 react 的第三方模块,借助这个模块可以实现动画切换效果。

安装:

yarn add react-transition-group

使用:

上面这张图描述了一个动画过渡的过程,它表示动画在入场阶段,透明度由0变为1,在出场阶段,透明度由1变为0。

接下来我们实现一下上述过程:

父组件:

import React, { Component } from 'react'
// CSSTransition 让元素有过渡效果,CSSTransition的子元素只能是一个
import { CSSTransition } from 'react-transition-group'
import './style/transistion.css'
class App extends Component {
state = {
  show: true
}
render() {
  const { show } = this.state
  return (
    <div>
      <button onClick={() => this.setState(state => ({ show: !state.show }))}>显示/隐藏</button>
      <hr />
      {/* 
        重要属性
        timeout 组件动画时长 必须要有的属性,单位是ms ,真实的动画还得看写css的动画时间,也就是说这里的事件要和css中写的动画时间保持一致
        in 动画开关,进场或出场  它的值是一个boolean,true:进入,false:退场
        classNames 指定动画的样式名称或样式定义的前缀名  {}|string,这个属性可以防止重名
        unmountOnExit 退场后,删除动画dom元素
        appear 第1次,访问时如果in为true,进行的动画
      */}
      <CSSTransition 
      in={show} 
      timeout={300} 
      classNames="fade"
      unmountOnExit={true}
      appear={true}
      >
        <div>
          <h3>我是内容</h3>
        </div>
      </CSSTransition>
    </div>
  )
}
}
export default App

css样式:

/* 进场起始和出场结束,透明度都是0 */
.fade-enter,
.fade-exit-done,
.fade-appear {
opacity: 0;
/* transform: scale(.6); */
}
/* 进场由0变为1的动画时间 */
.fade-enter-active,
.fade-appear-active {
opacity: 1;
/* transform: scale(1); */
transition: opacity 300ms;
}
/* 出场由1变为0的动画时间 */
.fade-exit-active {
opacity: 0;
/* transform: scale(.6); */
transition: all 300ms;
}

 

2. 将animate.css集成到csstranistion中

安装:

yarn add animate.css

使用:

父组件:

import React, { Component } from 'react'
// CSSTransition 让元素有过渡效果,CSSTransition子元素只能是一个
import { CSSTransition } from 'react-transition-group'
import 'animate.css'
// 注意这个文件要放在animate.css的下面,防止覆盖
import './style/transistion.css'
class App extends Component {
state = {
  show: true
}
render() {
  const { show } = this.state
  return (
    <div>
      <button onClick={() => this.setState(state => ({ show: !state.show }))}>显示/隐藏</button>
      <hr />
      {/* 
        重要属性
        timeout 组件动画时长 必须的属性  ms ,真实的动画还得看写css的动画时间
        in 动画开关,进场或出场  boolean true进入 false退场
        classNames 指定动画的样式名称或样式定义的前缀名  {}|string
        unmountOnExit 退场后,删除动画dom元素
      */}
      <CSSTransition
        in={show}
        timeout={300}
        // 自定义的类名
        classNames={{
          // 刚进入动画
          enter: 'animate__animated',
          // 刚退出动画
          exit: 'animate__animated',
          // 进入过程中
          enterActive: 'animate__fadeIn',
          // 退出过程中
          exitActive: 'animate__fadeOut'
        }}
        // 默认为真,即删除
        unmountOnExit
      >
        <div style={{ display: 'inline-block' }}>
          <h3>我是内容</h3>
        </div>
      </CSSTransition>
    </div>
  )
}
}
export default App

css样式:

:root {
/* 更改根节点中的元素的值 */
/* 动画持续时间 */
--animate-duration: 300ms;
/* 动画延迟 */
--animate-delay: 300ms;
}
/* 进场起始和出场结束,透明度都是0 */
.fade-enter,
.fade-exit-done,
.fade-appear {
opacity: 0;
/* transform: scale(.6); */
}
/* 进场由0变为1的动画时间 */
.fade-enter-active,
.fade-appear-active {
opacity: 1;
/* transform: scale(1); */
transition: opacity 300ms;
}
/* 出场由1变为0的动画时间 */
.fade-exit-active {
opacity: 0;
/* transform: scale(.6); */
transition: all 300ms;
}

 

3. 列表过渡

介绍:

当需要用到多个 css 动画过渡效果时,我们可以使用 TransitionGroup 组件将 CSSTransition 组件包裹起来,实现列表过渡。

注意:使用了 TransitionGroup 组件,则里面的 CSSTransition 属性中的 in 无效,要用唯一不重复的 key 来代替换,且 key 的值必须为字符串类型,否则报错。

使用:

父组件:

import React, { Component } from 'react'
// CSSTransition 让元素有过渡效果,CSSTransition子元素只能是一个
import { CSSTransition, TransitionGroup } from 'react-transition-group'
import './style/transistion.css'
class App extends Component {
state = {
  todos: []
}
render() {
  const { todos } = this.state
  return (
    <div>
      <TransitionGroup>
        {/* 使用了TransitionGroup组件,则里面的CSSTransition属性in无效,用要唯一不重复的key来代替换 */}
        {todos.map((item, index) => (
          <CSSTransition key={index + ''} timeout={300} classNames="fade" unmountOnExit>
            <div>
              <span>{item}</span>
              <span
                onClick={() => {
                  this.setState(state => ({
                    todos: state.todos.filter(val => val != item)
                  }))
                }}
              >
                -- 删除
              </span>
            </div>
          </CSSTransition>
        ))}
      </TransitionGroup>
      <hr />
      <button
        onClick={() => {
          this.setState(state => ({
            todos: [...state.todos, Date.now() + '']
          }))
        }}
      >
        添加任务
      </button>
    </div>
  )
}
}
export default App

css样式:

:root {
/* 更改根节点中的元素的值 */
/* 动画持续时间 */
--animate-duration: 300ms;
/* 动画延迟 */
--animate-delay: 300ms;
}
/* 进场起始和出场结束,透明度都是0 */
.fade-enter,
.fade-exit-done,
.fade-appear {
opacity: 0;
/* transform: scale(.6); */
}
/* 进场由0变为1的动画时间 */
.fade-enter-active,
.fade-appear-active {
opacity: 1;
/* transform: scale(1); */
transition: opacity 300ms;
}
/* 出场由1变为0的动画时间 */
.fade-exit-active {
opacity: 0;
/* transform: scale(.6); */
transition: all 300ms;
}

 

4. switchTransition动画

父组件:

import React, { Component } from 'react'
// CSSTransition 让元素有过渡效果,CSSTransition子元素只能是一个
import { CSSTransition, SwitchTransition } from 'react-transition-group'
import './style/transistion.css'
class App extends Component {
state = {
  on: true
}
render() {
  const { on } = this.state
  return (
    <div>
      {/* 
       动画切换的模式
        in-out  先进入,再退出
        out-in  先退出,再进入   默认值
      */}
      {/* <SwitchTransition mode='in-out'> */}
      <SwitchTransition mode='out-in'>
        {/* 在SwitchTransition中它要想有动画,用key */}
        <CSSTransition key={on ? 'a' : 'b'} timeout={300} classNames="fade">
          <h3 style={{ display: 'inline-block' }}>{on ? '你好' : '再见'}</h3>
        </CSSTransition>
      </SwitchTransition>
      <hr />
      <button
        onClick={() => {
          this.setState(state => ({
            on: !state.on
          }))
        }}
      >
        改变
      </button>
    </div>
  )
}
}
export default App

css样式:

:root {
/* 更改根节点中的元素的值 */
/* 动画持续时间 */
--animate-duration: 300ms;
/* 动画延迟 */
--animate-delay: 300ms;
}
/* 进场起始和出场结束,透明度都是0 */
.fade-enter,
.fade-exit-done,
.fade-appear {
opacity: 0;
transform: scale(.6);
}
/* 进场由0变为1的动画时间 */
.fade-enter-active,
.fade-appear-active {
opacity: 1;
transform: scale(1);
transition: opacity 300ms,transform 300ms;
}
/* 出场由1变为0的动画时间 */
.fade-exit-active {
opacity: 0;
/* transform: scale(.6); */
transition: all 300ms;
}

 

5. 路由切换过渡

父组件(注意这里的过渡动画样式 css 文件已在入口文件引入):

import React, { Component } from 'react'
import { Switch, Route, Link, withRouter } from 'react-router-dom'
import { CSSTransition, TransitionGroup } from 'react-transition-group'
import RenderCmp from './views/Render'
import Login from './views/Login'
@withRouter
class App extends Component {
render() {
  return (
    <div>
      <Link to="/login">login</Link> --
      <Link to="/render">render</Link>
      <hr />
      {/* 用 TransitionGroup 一包裹,就不用定义in属性了 */}
      <TransitionGroup>
        {/* 把路由地址当做唯一不可重复的key值 */}
        <CSSTransition timeout={300} key={this.props.location.key} classNames="router">
          <Switch>
            <Route path="/login" component={Login} />
            <Route path="/render" component={RenderCmp} />
          </Switch>
        </CSSTransition>
      </TransitionGroup>
    </div>
  )
}
}
export default App

css样式:

:root {
/* 更改根节点中的元素的值 */
/* 动画持续时间 */
--animate-duration: 300ms;
/* 动画延迟 */
--animate-delay: 300ms;
}
/* 进场起始和出场结束,透明度都是0 */
.fade-enter,
.fade-exit-done,
.fade-appear {
opacity: 0;
transform: scale(.6);
}
/* 进场由0变为1的动画时间 */
.fade-enter-active,
.fade-appear-active {
opacity: 1;
transform: scale(1);
transition: opacity 300ms,transform 300ms;
}
/* 出场由1变为0的动画时间 */
.fade-exit-active {
opacity: 0;
/* transform: scale(.6); */
transition: all 300ms;
}
/* ---------------------------------- */
.router-enter {
opacity: 0;
}
.router-enter-active {
opacity: 1;
transition: all 300ms;
}
.router-exit-active {
opacity: 0;
transition: all 0ms;
}

 

6. 高阶组件实现路由切换过渡

介绍:

有些时候路由会特别多,而有些路由需要动画,有些则不需要,我们可以使用高阶组件,将需要过渡动画的路由用高阶组件包裹,没有包裹的路由则没有过渡动画。

使用:

父组件:

import React, { Component } from 'react'
import { Route, Link, withRouter } from 'react-router-dom'
import RenderCmp from './views/Render'
import Login from './views/Login'
@withRouter
class App extends Component {
render() {
  return (
    <div>
      <Link to="/login">login</Link> --
      <Link to="/render">render</Link>
      <hr />
      {/* 这里用 children 渲染方式,因为这种渲染方式,无论路由是否匹配到,路由对应的组件都在,都在才能添加动画效果 */}
      <Route path="/login" children={router => <Login {...router} />} />
      <Route path="/render" children={router => <RenderCmp {...router} />} />
    </div>
  )
}
}
export default App

子组件:

import React, { Component } from 'react'
import withTransition from '../../hoc/withTransition'
@withTransition
class Login extends Component {
render() {
  return (
    <div>
      <h3>用户登录</h3>
      <button
        onClick={() => {
          sessionStorage.setItem('uid', 1)
          this.props.history.push('/render')
        }}
      >
        登录一下
      </button>
    </div>
  )
}
}
export default Login

定义高阶组件:

import React, { Component } from 'react';
import { CSSTransition } from 'react-transition-group'
const withTransition = Cmp => {
return class extends Component {
  render() {
    return (
      <>
        <CSSTransition
          in={this.props.match ? true : false}
          timeout={300}
          classNames='fade'
          unmountOnExit
        >
          <>
            {this.props.match
              ? <Cmp {...this.props} /> : <div></div>}
          </>
        </CSSTransition>
      </>
    );
  }
}
}
export default withTransition

css样式:

.router-enter {
opacity: 0;
}
.router-enter-active {
opacity: 1;
transition: all 300ms;
}
.router-exit-active {
opacity: 0;
transition: all 0ms;
}

关于React过渡动画组件基础使用介绍的文章就介绍至此,更多相关React过渡动画内容请搜索编程宝库以前的文章,希望以后支持编程宝库

在纯静态网站里,有时候会动态更新某个区域往会选择 Pjax(swup、barba.js)去处理,他们都是使用 ajax 和 pushState 通过真正的永久链接,页面标题和后退按钮提供快速浏览体验。但 ...