• React-18(组件化开发)--ref与react过渡动画


    React

    React的更新流程

    React在props或state发生改变时,会调用React的render方法,会创建一颗不同的树。

    Reactt需要基于这两颗不同的树之间的差别来判断如何有效的更新UI:
    如果一棵树参考另外一棵树进行完全比较更新,那么即使是最先进的算法,该算法的复杂程度为 O(n³),其中 n 是树中元素的数量;
    如果在 React 中使用了该算法,那么展示 1000 个元素所需要执行的计算量将在十亿的量级范围;
    这个开销太过昂贵了,React的更新性能会变得非常低效;

    于是,React对这个算法进行了优化,将其优化成了O(n),如何优化的呢?
    同层节点之间相互比较,不会垮节点比较;
    不同类型的节点,产生不同的树结构;
    开发中,可以通过key来指定哪些节点在不同的渲染下保持稳定;

    keys的优化

    我们在前面遍历列表时,总是会提示一个警告,让我们加入一个key属性:
    方式一:在最后位置插入数据
    这种情况,有无key意义并不大

    方式二:在前面插入数据
    这种做法,在没有key的情况下,所有的li都需要进行修改;

    当子元素(这里的li)拥有 key 时,React 使用 key 来匹配原有树上的子元素以及最新树上的子元素:
    在下面这种场景下,key为111和222的元素仅仅进行位移,不需要进行任何的修改;
    将key为333的元素插入到最前面的位置即可;

    key的注意事项:
    key应该是唯一的;
    key不要使用随机数(随机数在下一次render时,会重新生成一个数字);
    使用index作为key,对性能是没有优化的;

    事实上,很多的组件没有必须要重新render;
    它们调用render应该有一个前提,就是依赖的数据(state、props)发生改变时,再调用自己的render方法;

    如何来控制render方法是否被调用呢?
    通过shouldComponentUpdate方法即可;

    shouldComponentUpdate

    React给我们提供了一个生命周期方法 shouldComponentUpdate(很多时候,我们简称为SCU),这个方法接受参数,并且需要有返回值:

    该方法有两个参数:
    参数一:nextProps 修改之后,最新的props属性
    参数二:nextState 修改之后,最新的state属性

    该方法返回值是一个boolean类型
    返回值为true,那么就需要调用render方法;
    返回值为false,那么久不需要调用render方法;
    默认返回的是true,也就是只要state发生改变,就会调用render方法;

    比如我们在App中增加一个message属性:
    jsx中并没有依赖这个message,那么它的改变不应该引起重新渲染;
    但是因为render监听到state的改变,就会重新render,所以最后render方法还是被重新调用了;

    PureComponent

    如果所有的类,我们都需要手动来实现 shouldComponentUpdate,那么会给我们开发者增加非常多的工作量。
    我们来设想一下shouldComponentUpdate中的各种判断的目的是什么?
    props或者state中的数据是否发生了改变,来决定shouldComponentUpdate返回true或者false;

    事实上React已经考虑到了这一点,所以React已经默认帮我们实现好了,如何实现呢?
    将class继承自PureComponent。

    shallowEqual

    这个方法中,调用 !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState),这个shallowEqual就是
    进行浅层比较

    memo

    目前我们是针对类组件可以使用PureComponent,那么函数式组件呢?
    事实上函数式组件我们在props没有改变时,也是不希望其重新渲染其DOM树结构的

    React.memo() 是一个高阶组件
    它接收另一个组件作为参数,并且会返回一个包装过的新组件
    包装过的新组件就会具有缓存功能,
    包装过后,只有组件的props发生变化
    才会触发组件的重新的渲染,否则总是返回缓存中结果
    我们可以使用高阶组件memo进行一层包裹

    ref

    在React的开发模式中,通常情况下不需要、也不建议直接操作DOM原生,但是某些特殊的情况,确实需要获取到DOM进行某些操作:
    管理焦点,文本选择或媒体播放;
    触发强制动画;
    集成第三方 DOM 库;
    我们可以通过refs获取DOM;

    如何创建refs来获取对应的DOM呢?目前有三种方式:
    方式一:传入字符串
    使用时通过 this.refs.传入的字符串格式获取对应的元素;
    方式二:传入一个对象
    对象是通过 React.createRef() 方式创建出来的;
    使用时获取到创建的对象其中有一个current属性就是对应的元素;
    方式三:传入一个函数
    该函数会在DOM被挂载时进行回调,这个函数会传入一个 元素对象,我们可以自己保存;
    使用时,直接拿到之前保存的元素对象即可;

    import React, { PureComponent, createRef } from 'react'
    
    export class App extends PureComponent {
      constructor() {
        super()
    
        this.state = {
    
        }
    
        this.titleRef = createRef()
        this.titleEl = null
      }
    
      getNativeDOM() {
        // 1.方式一: 在React元素上绑定一个ref字符串
        // console.log(this.refs.kobe)
    
        // 2.方式二: 提前创建好ref对象, createRef(), 将创建出来的对象绑定到元素
        // console.log(this.titleRef.current)
    
        // 3.方式三: 传入一个回调函数, 在对应的元素被渲染之后, 回调函数被执行, 并且将元素传入
        console.log(this.titleEl)
      }
    
      render() {
        return (
          <div>
            <h2 ref="kobe">Hello World</h2>
            <h2 ref={this.titleRef}>你好啊,李银河</h2>
            <h2 ref={el => this.titleEl = el}>你好啊, 师姐</h2>
            <button onClick={e => this.getNativeDOM()}>获取DOM</button>
          </div>
        )
      }
    }
    
    export default App
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

    ref的类型

    ref 的值根据节点的类型而有所不同:
    当 ref 属性用于 HTML 元素时,构造函数中使用 React.createRef() 创建的 ref 接收底层 DOM 元素作为其 current 属性;
    当 ref 属性用于自定义 class 组件时,ref 对象接收组件的挂载实例作为其 current 属性;
    你不能在函数组件上使用 ref 属性,因为他们没有实例;

    import React, { PureComponent, createRef } from 'react'
    
    
    class HelloWorld extends PureComponent {
      test() {
        console.log("test------")
      }
    
      render() {
        return <h1>Hello World</h1>
      }
    }
    
    export class App extends PureComponent {
      constructor() {
        super()
    
        this.hwRef = createRef()
      }
    
      getComponent() {
        console.log(this.hwRef.current)
        this.hwRef.current.test()
      }
    
      render() {
        return (
          <div>
            <HelloWorld ref={this.hwRef}/>
            <button onClick={e => this.getComponent()}>获取组件实例</button>
          </div>
        )
      }
    }
    
    export default App
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36

    函数式组件是没有实例的,所以无法通过ref获取他们的实例:
    但是某些时候,我们可能想要获取函数式组件中的某个DOM元素;
    这个时候我们可以通过 React.forwardRef

    import React, { PureComponent, createRef, forwardRef } from 'react'
    
    
    const HelloWorld = forwardRef(function(props, ref) {
      return (
        <div>
          <h1 ref={ref}>Hello World</h1>
          <p>哈哈哈</p>
        </div>
      )
    })
    
    
    export class App extends PureComponent {
      constructor() {
        super()
    
        this.hwRef = createRef()
      }
    
      getComponent() {
        console.log(this.hwRef.current)
      }
    
      render() {
        return (
          <div>
            <HelloWorld ref={this.hwRef}/>
            <button onClick={e => this.getComponent()}>获取组件实例</button>
          </div>
        )
      }
    }
    
    export default App
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    严格模式检查的是什么

    但是检测,到底检测什么呢?
    1.识别不安全的生命周期:
    2.使用过时的ref API
    3.检查意外的副作用
    这个组件的constructor会被调用两次;
    这是严格模式下故意进行的操作,让你来查看在这里写的一些逻辑代码被调用多次时,是否会产生一些副作用;
    在生产环境中,是不会被调用两次的;
    4.使用废弃的findDOMNode方法
    在之前的React API中,可以通过findDOMNode来获取DOM,不过已经不推荐使用了,可以自行学习演练一下
    5.检测过时的context API

    react-transition-group

    使用react-transition-group来完成过渡动画
    npm install react-transition-group --save
    react-transition-group本身非常小,不会为我们应用程序增加过多的负担。

    react-transition-group主要组件

    react-transition-group主要包含四个组件:
    Transition
    该组件是一个和平台无关的组件(不一定要结合CSS);
    在前端开发中,我们一般是结合CSS来完成样式,所以比较常用的是CSSTransition;
    CSSTransition
    在前端开发中,通常使用CSSTransition来完成过渡动画效果
    SwitchTransition
    两个组件显示和隐藏切换时,使用该组件
    TransitionGroup
    将多个动画组件包裹在其中,一般用于列表中元素的动画;

    CSSTransition

    CSSTransition是基于Transition组件构建的:
    CSSTransition执行过程中,有三个状态:appear、enter、exit;
    它们有三种状态,需要定义对应的CSS样式:
    第一类,开始状态:对于的类是-appear、-enter、exit;
    第二类:执行动画:对应的类是-appear-active、-enter-active、-exit-active;
    第三类:执行结束:对应的类是-appear-done、-enter-done、-exit-done;

    CSSTransition常见对应的属性:
    in:触发进入或者退出状态
    如果添加了unmountOnExit={true},那么该组件会在执行退出动画结束后被移除掉;
    当in为true时,触发进入状态,会添加-enter、-enter-acitve的class开始执行动画,当动画执行结束后,会移除两个class,并且添加-enter-done的class;
    当in为false时,触发退出状态,会添加-exit、-exit-active的class开始执行动画,当动画执行结束后,会移除两个class,并且添加-enter-done的class;
    classNames:动画class的名称
    决定了在编写css时,对应的class名称:比如card-enter、card-enter-active、card-enter-done;
    timeout:
    过渡动画的时间
    appear:
    是否在初次进入添加动画(需要和in同时为true)
    unmountOnExit:退出后卸载组件

    CSSTransition对应的钩子函数:主要为了检测动画的执行过程,来完成一些JavaScript的操作
    onEnter:在进入动画之前被触发;
    onEntering:在应用进入动画时被触发;
    onEntered:在应用进入动画结束后被触发;

    import React, { createRef, PureComponent } from 'react'
    import { CSSTransition } from "react-transition-group"
    import "./style.css"
    
    export class App extends PureComponent {
      constructor(props) {
        super(props)
    
        this.state = {
          isShow: true
        }
    
        this.sectionRef = createRef()
      }
    
      render() {
        const { isShow } = this.state
    
        return (
          <div>
            <button onClick={e => this.setState({isShow: !isShow})}>切换</button>
            {/* { isShow && 

    哈哈哈

    } */
    } <CSSTransition nodeRef={this.sectionRef} in={isShow} unmountOnExit={true} classNames="why" timeout={2000} appear onEnter={e => console.log("开始进入动画")} onEntering={e => console.log("执行进入动画")} onEntered={e => console.log("执行进入结束")} onExit={e => console.log("开始离开动画")} onExiting={e => console.log("执行离开动画")} onExited={e => console.log("执行离开结束")} > <div className='section' ref={this.sectionRef}> <h2>哈哈哈</h2> <p>我是内容, 哈哈哈</p> </div> </CSSTransition> </div> ) } } export default App
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    /* 进入动画 */
    /* .why-appear {
      transform: translateX(-150px);
    }
    
    .why-appear-active {
      transform: translateX(0);
      transition: transform 2s ease;
    } */
    
    .why-appear, .why-enter {
      opacity: 0;
    }
    
    .why-appear-active, .why-enter-active {
      opacity: 1;
      transition: opacity 2s ease;
    }
    
    /* 离开动画 */
    .why-exit {
      opacity: 1;
    }
    
    .why-exit-active {
      opacity: 0;
      transition: opacity 2s ease;
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    SwitchTransition

    SwitchTransition可以完成两个组件之间切换的炫酷动画:
    比如我们有一个按钮需要在on和off之间切换,我们希望看到on先从左侧退出,off再从右侧进入;
    这个动画在vue中被称之为 vue transition modes;
    react-transition-group中使用SwitchTransition来实现该动画;
    SwitchTransition中主要有一个属性:mode,有两个值
    in-out:表示新组件先进入,旧组件再移除;
    out-in:表示旧组件先移除,新组建再进入;
    如何使用SwitchTransition呢?
    SwitchTransition组件里面要有CSSTransition或者Transition组件,不能直接包裹你想要切换的组件;
    SwitchTransition里面的CSSTransition或Transition组件不再像以前那样接受in属性来判断元素是何种状态,取而代之的是key属性

    import React, { PureComponent } from 'react'
    import { SwitchTransition, CSSTransition } from 'react-transition-group'
    import "./style.css"
    
    export class App extends PureComponent {
      constructor() {
        super() 
    
        this.state = {
          isLogin: true
        }
      }
    
      render() {
        const { isLogin } = this.state
    
        return (
          <div>
            <SwitchTransition mode='out-in'>
              <CSSTransition
                key={isLogin ? "exit": "login"}
                classNames="login"
                timeout={1000}
              >
                <button onClick={e => this.setState({ isLogin: !isLogin })}>
                  { isLogin ? "退出": "登录" }
                </button>
              </CSSTransition>
            </SwitchTransition>
          </div>
        )
      }
    }
    
    export default App
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    .login-enter {
      transform: translateX(100px);
      opacity: 0;
    }
    
    .login-enter-active {
      transform: translateX(0);
      opacity: 1;
      transition: all 1s ease;
    }
    
    .login-exit {
      transform: translateX(0);
      opacity: 1;
    }
    
    .login-exit-active {
      transform: translateX(-100px);
      opacity: 0;
      transition: all 1s ease;
    }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    TrajnsitionGroup

    当我们有一组动画时,需要将这些CSSTransition放入到一个TransitionGroup中来完成动画:

    import React, { PureComponent } from 'react'
    import { TransitionGroup, CSSTransition } from "react-transition-group"
    import "./style.css"
    
    export class App extends PureComponent {
      constructor() {
        super()
    
        this.state = {
          books: [
            { id: 111, name: "你不知道JS", price: 99 },
            { id: 222, name: "JS高级程序设计", price: 88 },
            { id: 333, name: "Vuejs高级设计", price: 77 },
          ]
        }
      }
    
      addNewBook() {
        const books = [...this.state.books]
        books.push({ id: new Date().getTime(), name: "React高级程序设计", price: 99 })
        this.setState({ books })
      }
    
      removeBook(index) {
        const books = [...this.state.books]
        books.splice(index, 1)
        this.setState({ books })
      }
    
      render() {
        const { books } = this.state
    
        return (
          <div>
            <h2>书籍列表:</h2>
            <TransitionGroup component="ul">
              {
                books.map((item, index) => {
                  return (
                    <CSSTransition key={item.id} classNames="book" timeout={1000}>
                      <li>
                        <span>{item.name}-{item.price}</span>
                        <button onClick={e => this.removeBook(index)}>删除</button>
                      </li>
                    </CSSTransition>
                  )
                })
              }
            </TransitionGroup>
            <button onClick={e => this.addNewBook()}>添加新书籍</button>
          </div>
        )
      }
    }
    
    export default App
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    .book-enter {
      transform: translateX(150px);
      opacity: 0;
    }
    
    .book-enter-active {
      transform: translateX(0);
      opacity: 1;
      transition: all 1s ease;
    }
    
    .book-exit {
      transform: translateX(0);
      opacity: 1;
    }
    
    .book-exit-active {
      transform: translateX(150px);
      opacity: 0;
      transition: all 1s ease;
    }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
  • 相关阅读:
    Acwing 802. 区间和
    算法刷题第十一天:递归 / 回溯--2
    【操作系统】聊聊文件系统是如何工作的
    SCM供应链具体有哪些优越性?智能供应链管理系统助力汽车服务企业数字化转型
    js之页面列表加载常用方法总结
    简易版剪辑视频程序(python-VideoFileClip)
    【无标题】
    Si3262 集成低功耗SOC 三合一智能门锁应用芯片
    故障:不能打开 Office 应用程序,并指示有账户正在登录
    提示学习用于推荐系统问题(PPR,PFRec)
  • 原文地址:https://blog.csdn.net/weixin_65402230/article/details/128192743