zoukankan      html  css  js  c++  java
  • 【React源码解读】react-ref && forward-ref

    react-ref

    源码地址:https://github.com/facebook/react/blob/master/packages/react/src/ReactCreateRef.js

    三种使用ref方式

    • string ref (不被推荐的方式,废弃)

    react会在完成这个节点渲染之后,会在this.refs这个对象上挂载这个string对应的一个key,这个key所指向的就是这个节点的实例对象,如果是dom节点就会对应dom的实例,如果是子组件,就会是子组件的实例(也就是class component) 如果是一个function component,正常来讲是会失败的,也就是undefined

    • function
    • createRef

    使用createRef创建一个对象,这个对象初始的时候,里面的current是null,把这个对象传到某个节点,在这个组件渲染之后,会把这个节点挂载到这个对象的current

    // demo
    import React from 'react'
    
    export default class RefDemo extends React.Component {
      constructor() {
        super()
        this.objRef = React.createRef()
    
        // { current: null }
      }
    
      componentDidMount() {
        // console.log(`span1: ${this.refs.ref1.textContent}`)
        // console.log(`span2: ${this.ref2.textContent}`)
        // console.log(`span3: ${this.ref3.current.textContent}`)
        setTimeout(() => {
          this.refs.stringRef.textContent = 'string ref got' 
          this.methodRef.textContent = 'method ref got'
          this.objRef.current.textContent = 'obj ref got'
        }, 1000)
      }
    
      render() {
        return (
          <>
            <p ref="stringRef">span1</p>
            <p ref={ele => (this.methodRef = ele)}>span3</p>
            <p ref={this.objRef}>span3</p>
          </>
        )
      }
    }
    
    // export default () => {
    //   return <div>Ref</div>
    // }
    
    
    

    demo能看到三种方式都成功获取到了节点,并更新了节点的值

    // 源码解读
    import type {RefObject} from 'shared/ReactTypes';
    
    // an immutable object with a single mutable value
    export function createRef(): RefObject {
      const refObject = {
        current: null,
      };
      if (__DEV__) {
        Object.seal(refObject);
      }
      return refObject;
    }
    
    
    

    源码其实就这短短几行,返回了一个对象,这个对象中有个current属性,初始为null

    存储一个疑问:这个对象后期如何使用,如何挂载节点?

    forward-ref

    源码学习地址:https://github.com/facebook/react/blob/master/packages/react/src/forwardRef.js

    考虑如下场景

    我们是一个组件开发者,写了很多供用户使用的开源组件。用户使用了例如redux的connect连接组件,connect其实是hoc的模式包裹了一层组件,那么如果用户在connect的组件上使用ref,就无法直接挂载到真实组件上。

    因此

    可以考虑使用React.forwardRef(props, ref) 去传递一层ref

    // demo
    import React from 'react'
    
    const TargetComponent = React.forwardRef((props, ref) => (
      <input type="text" ref={ref} />
    ))
    
    export default class Comp extends React.Component {
      constructor() {
        super()
        this.ref = React.createRef()
      }
    
      componentDidMount() {
        this.ref.current.value = 'ref get input'
      }
    
      render() {
        return <TargetComponent ref={this.ref} />
      }
    }
    
    
    // 源码解读
    import {REACT_FORWARD_REF_TYPE} from 'shared/ReactSymbols';
    
    import warningWithoutStack from 'shared/warningWithoutStack';
    
    export default function forwardRef<Props, ElementType: React$ElementType>(
      render: (props: Props, ref: React$Ref<ElementType>) => React$Node,
    ) {
      
      ... 
      
      return {
        $$typeof: REACT_FORWARD_REF_TYPE,
        render,
      };
    }
    
    /**
    返回的是一个对象,对象中有个$$typeof,切忌不能与createElement中的$$typeof弄混。
    
    拿上述demo来说,由于通过React.forwardRef返回的是一个对象,因此TargetComponent也是一个对象,而在<TargetComponent />从jsx解析为js中,解析为React.createElement(type, config, children)中,TargetComponent只是作为type。
    
    因此
    
    使用React.forwardRef返回的$$typeof仍然是REACT_ELEMENT_TYPE,它的type是我们拿到的对象{
        $$typeof: REACT_FORWARD_REF_TYPE,
        render,
      };
    它里面有个$$typeof,是REACT_FORWARD_REF_TYPE
    
    小结:我们使用React.forwardRef创建的所有的节点,它的$$typeof都是REACT_ELEMENT_TYPE
    
    */
    
    
  • 相关阅读:
    Java类 初始化块
    Java中 equals和==
    Raft算法
    OLTP与OLAP
    数据库事务机制ACID
    乐观锁和悲观锁
    SparkStreaming + Flume
    如何提高深度睡眠质量,科学解决睡眠问题
    centos 7 下安装mysql 远程连接出现10038错误如何解决
    CentOS 7.0 yum安装Apache、PHP和MySQL
  • 原文地址:https://www.cnblogs.com/fe-linjin/p/11716827.html
Copyright © 2011-2022 走看看