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

   2023-02-08 学习力0
核心提示:目录1. 基础使用2. 将animate.css集成到csstranistion中3. 列表过渡4. switchTransition动画5. 路由切换过渡6. 高阶组件实现路由切换过渡1. 基础使用介绍:在项目中可能会给一些组件的显示或隐藏添加某种过渡动画,这样可以很好的增加用户的使用体验, react-

1. 基础使用

介绍:

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

安装:

yarn add react-transition-group

使用:

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

上面这张图描述了一个动画过渡的过程,它表示动画在入场阶段,透明度由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;
}

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

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;
}

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

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;
}

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

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;
}

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

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;
}

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

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过渡动画组件基础使用介绍

原文地址:https://blog.csdn.net/weixin_45605541/article/details/127098884
 
反对 0举报 0 评论 0
 

免责声明:本文仅代表作者个人观点,与乐学笔记(本网)无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
    本网站有部分内容均转载自其它媒体,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责,若因作品内容、知识产权、版权和其他问题,请及时提供相关证明等材料并与我们留言联系,本网站将在规定时间内给予删除等相关处理.

  • React实现基于Antd密码强度校验组件示例详解
    React实现基于Antd密码强度校验组件示例详解
    目录引言效果预览组件思想组件开发引言最近在开发 Nest 和 Umi 技术栈的个人项目,在用户管理模块需要用到一个密码强度校验组件,在网上寻找一方资料,没有找到自己想要的,特此自己造轮子!效果预览组件思想既然是密码强度校验,那么强度就必须有个梯度,这
    03-16
  • 03 React快速入门(三)——实现从一个输入框中添加完数据后此输入框内容清除的功能
    03 React快速入门(三)——实现从一个输入框中
    功能描述:      我们在一个输入框输入内容,然后点击添加按钮,此输入框的内容就会添加到页面上,但是此输入框中还存在上次输入的内容,我们想在每次输入添加完成之后,此输入框中的内容就会清除,如图:   实现思路:      我们可以先在输入框上定
    03-08
  • react编译器jsxTransformer,babel
    1.JSX是什么JSX其实是JavaScript的扩展,React为了代码的可读性更方便地创建虚拟DOM等原因,加入了一些类似XML的语法的扩展。2.编译器——jsxTransformerJSX代码并不能直接运行,需要将它编译成正常的JavaScript表达式才能运行,jsxTransformer.js就是这一编
    03-08
  • G2( bizCharts ) React 绘制混合图例
    G2( bizCharts ) React 绘制混合图例
     G2( bizCharts ) React 绘制混合图例,// data-set 可以按需引入,除此之外不要引入别的包import React from 'react';import { Chart, Axis, Tooltip, Geom, Legend, Label } from 'bizcharts';import DataSet from '@antv/data-set';// 下面的代码会被作为
    03-08
  • React-多页面应用 react怎么写页面
    React-多页面应用 react怎么写页面
    1初始化项目npm init create-react-app my-app2.修改indeximport React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './App';ReactDOM.render(App /, document.getElementById('root')
    03-08
  • react-native start 启动错误解决方法
    ERRORError watching file for changes: EMFILE{"code":"EMFILE","errno":"EMFILE","syscall":"Error watching file for changes:","filename":null}Error: Error watching file for changes: EMFILE
    03-08
  • React兄弟组件通信(发布者-订阅者模式)
    // eventProxy.js'use strict';const eventProxy = {onObj: {},oneObj: {},on: function(key, fn) {if(this.onObj[key] === undefined) {this.onObj[key] = [];}this.onObj[key].push(fn);},one: function(key, fn) {if(this.oneObj[key] === undefined) {thi
    03-08
  • React笔记_(7)_react路由 react路由配置
    路由路由(routing)是指分组从源到目的地时,决定端到端路径的网络范围的进程。路由器当然是作为一个转发设备出现的,主要是转发数据包来实现网络互联。那么react的路由到底指的是什么呢?举个栗子~~~在网页中点击后,从A页面跳到B页面,跳转过程中url发生变
    03-08
  • react-native关闭所有黄色警告 react native st
     将以下这两句话加在index.js(入口文件)中,放在AppRegistry.registerComponent('App', () = App)之前即可1 console.ignoredYellowBox = ['Warning: BackAndroid is deprecated. Please use BackHandler instead.','source.uri should not be an empty str
    03-08
  • react中style的写法 react styles
    div style={{width: 20px; height=30px}}style的写法/div 
    03-08
点击排行