溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

React中的ref怎么使用

發(fā)布時(shí)間:2023-01-06 09:42:15 來源:億速云 閱讀:94 作者:iii 欄目:web開發(fā)

這篇文章主要介紹“React中的ref怎么使用”的相關(guān)知識(shí),小編通過實(shí)際案例向大家展示操作過程,操作方法簡單快捷,實(shí)用性強(qiáng),希望這篇“React中的ref怎么使用”文章能幫助大家解決問題。

1. ref 的理解與使用

對于 Ref 的理解,要從兩個(gè)角度去分析:

  • Ref 對象的創(chuàng)建:使用 createRefuseRef 創(chuàng)建 Ref 對象 

  • React 本身對 Ref 的處理:對于標(biāo)簽中的 ref 屬性,React 是如何處理的

1.1. ref 對象的創(chuàng)建

1.1.1. createRef

在類組件中,我們會(huì)通過 createRef 去創(chuàng)建一個(gè) Ref 對象,其會(huì)被保存在類組件實(shí)例上,它的實(shí)現(xiàn)很簡單

packages/react/src/ReactCreateRef.js

export function createRef(): RefObject {
  const refObject = {
    current: null,
  }

  return refObject
}

可以看到,就是創(chuàng)建了一個(gè)包含 current 屬性的對象,僅此而已

1.1.2. useRef

這也就意味著我們不能在函數(shù)組件中使用 createRef,因?yàn)槊看魏瘮?shù)組件渲染都是一次新的函數(shù)執(zhí)行,每次執(zhí)行 createRef 得到的都是一個(gè)新的對象,無法保留其原來的引用

所以在函數(shù)組件中,我們會(huì)使用 useRef 創(chuàng)建 Ref 對象,React 會(huì)將 useRef 和函數(shù)組件對應(yīng)的 fiber 對象關(guān)聯(lián),將 useRef 創(chuàng)建的 ref 對象掛載到對應(yīng)的 fiber 對象上

這樣一來每次函數(shù)組件執(zhí)行,只要函數(shù)組件不被銷毀,那么對應(yīng)的 fiber 對象實(shí)例也會(huì)一直存在,所以 ref 也能夠被保留下來

1.2. React 對標(biāo)簽中 ref 屬性的處理

首先要明確一個(gè)結(jié)論,在 React 中獲取 DOM 元素或者組件實(shí)例并不是只能通過 ref 對象獲取?。?!

也就是說并不是只能通過先調(diào)用 createRef 創(chuàng)建 ref 對象,然后將它賦值到要獲取的元素或組件實(shí)例的 ref 屬性上,實(shí)際上還有別的方式

:::tip

只有類組件才有獲取組件實(shí)例這一說法,函數(shù)組件沒有實(shí)例,不能被 ref 標(biāo)記,但是可以通過 forwardRef 結(jié)合 useImperativeHandle 給函數(shù)組件賦予 ref 標(biāo)記的

:::

1.2.1. string ref

當(dāng)我們給元素或類組件標(biāo)簽中的 ref 屬性傳遞字符串時(shí),能夠在組件實(shí)例的 this.refs 中訪問到

class Child extends React.Component<PropsWithChildren> {
  render(): React.ReactNode {
    const { children } = this.props

    return (
      <div>
        <p>Child</p>
        {children}
      </div>
    )
  }
}

/** @description ref 屬性傳遞字符串 */
class RefDemo1 extends React.Component {
  logger = createLoggerWithScope('RefDemo1')

  componentDidMount(): void {
    this.logger.log(this.refs)
  }

  render(): React.ReactNode {
    return (
      <>
        <div ref="refDemo1DOM">ref 屬性傳遞字符串獲取 DOM 元素</div>
        <Child ref="refDemo1Component">ref 屬性傳遞字符串獲取類組件實(shí)例</Child>
      </>
    )
  }
}

React中的ref怎么使用

:::warning

這種方式已經(jīng)被 React 官方廢棄,盡量不要使用

:::

1.2.2. callback ref

ref 屬性傳遞函數(shù)時(shí),會(huì)在 commit 階段創(chuàng)建真實(shí) DOM 時(shí)執(zhí)行 ref 指定的函數(shù),并將元素作為第一個(gè)參數(shù)傳入,此時(shí)我們就可以利用它進(jìn)行賦值以獲取 DOM 元素或組件實(shí)例

/** @description ref 屬性傳遞函數(shù) */
class RefDemo2 extends React.Component {
  logger = createLoggerWithScope('RefDemo2')

  refDemo2DOM: HTMLElement | null = null
  refDemo2Component: Child | null = null

  componentDidMount(): void {
    this.logger.log(this.refDemo2DOM)
    this.logger.log(this.refDemo2Component)
  }

  render(): React.ReactNode {
    return (
      <>
        <div ref={(el) => (this.refDemo2DOM = el)}>
          ref 屬性傳遞函數(shù)獲取 DOM 元素
        </div>

        <Child ref={(child) => (this.refDemo2Component = child)}>
          ref 屬性傳遞函數(shù)獲取類組件實(shí)例
        </Child>
      </>
    )
  }
}

React中的ref怎么使用

1.2.3. object ref

這種方式就是我們最常用的方式了,使用 createRef 或者 useRef 創(chuàng)建 Ref 對象,并將其傳給標(biāo)簽的 ref 屬性即可

這種方式獲取到的 ref 需要先調(diào)用 current 屬性才能獲取到對應(yīng)的 DOM 元素或組件實(shí)例

/** @description ref 屬性傳遞對象 */
class RefDemo3 extends React.Component {
  logger = createLoggerWithScope('RefDemo3')

  refDemo3DOM = React.createRef<HTMLDivElement>()
  refDemo3Component = React.createRef<Child>()

  componentDidMount(): void {
    this.logger.log(this.refDemo3DOM)
    this.logger.log(this.refDemo3Component)
  }

  render(): React.ReactNode {
    return (
      <>
        <div ref={this.refDemo3DOM}>ref 屬性傳遞對象獲取 DOM 元素</div>

        <Child ref={this.refDemo3Component}>
          ref 屬性傳遞對象獲取類組件實(shí)例
        </Child>
      </>
    )
  }
}

2. ref 高階用法

2.1. forwardRef 轉(zhuǎn)發(fā) ref

2.1.1. 跨層級(jí)獲取

想要在爺組件中通過在子組件中傳遞 ref 獲取到孫組件的某個(gè)元素,也就是在爺組件中獲取到了孫組件的元素,是一種跨層級(jí)獲取

/** @description 孫組件 */
const Child: React.FC<{ grandRef: LegacyRef<HTMLDivElement> }> = (props) => {
  const { grandRef } = props

  return (
    <>
      <p>Child</p>
      <div ref={grandRef}>要獲取的目標(biāo)元素</div>
    </>
  )
}

/**
 * @description 父組件
 *
 * 第一個(gè)泛型參數(shù)是 ref 的類型
 * 第二個(gè)泛型參數(shù)是 props 的類型
 */
const Father = forwardRef<HTMLDivElement, {}>((props, ref) => {
  return (
    <div>
      <Child grandRef={ref} />
    </div>
  )
})

/** @description 爺組件 */
const GrandFather: React.FC = () => {
  let grandChildDiv: HTMLDivElement | null = null

  useEffect(() => {
    logger.log(grandChildDiv)
  }, [])

  return (
    <div>
      <Father ref={(el) => (grandChildDiv = el)} />
    </div>
  )
}

2.1.2. 合并轉(zhuǎn)發(fā)自定義 ref

forwardRef 不僅可以轉(zhuǎn)發(fā) ref 獲取 DOM 元素和組件實(shí)例,還可以轉(zhuǎn)發(fā)合并后的自定義 ref

什么是“合并后的自定義 ref”呢?通過一個(gè)場景來看看就明白了

:::info{title=場景}

通過給 Foo 組件綁定 ref,獲取多個(gè)內(nèi)容,包括:

  • 子組件 Bar 的組件實(shí)例

  • Bar 組件中的 DOM 元素 button

  • 孫組件 Baz 的組件實(shí)例

:::

這種在一個(gè) ref 里能夠訪問多個(gè)元素和實(shí)例的就是“合并后的自定義 ref”

/** @description 自定義 ref 的類型 */
interface CustomRef {
  bar: Bar
  barButton: HTMLButtonElement
  baz: Baz
}

class Baz extends React.Component {
  render(): React.ReactNode {
    return <div>Baz</div>
  }
}

class Bar extends React.Component<{
  customRef: ForwardedRef<CustomRef>
}> {
  buttonEl: HTMLButtonElement | null = null
  bazInstance: Baz | null = null

  componentDidMount(): void {
    const { customRef } = this.props

    if (customRef) {
      ;(customRef as MutableRefObject<CustomRef>).current = {
        bar: this,
        barButton: this.buttonEl!,
        baz: this.bazInstance!,
      }
    }
  }

  render() {
    return (
      <>
        <button ref={(el) => (this.buttonEl = el)}>Bar button</button>
        <Baz ref={(instance) => (this.bazInstance = instance)} />
      </>
    )
  }
}
const FowardRefBar = forwardRef<CustomRef>((props, ref) => (
  <Bar {...props} customRef={ref} />
))

const Foo: React.FC = () => {
  const customRef = useRef<CustomRef>(null)

  useEffect(() => {
    logger.log(customRef.current)
  }, [])

  return <FowardRefBar ref={customRef} />
}

React中的ref怎么使用

2.1.3. 高階組件轉(zhuǎn)發(fā) ref

如果我們在高階組件中直接使用 ref,它會(huì)直接指向 WrapComponent

class TestComponent extends React.Component {
  render(): React.ReactNode {
    return <p>TestComponent</p>
  }
}

/** @description 不使用 forwardRef 轉(zhuǎn)發(fā) HOC 中的 ref */
const HOCWithoutForwardRef = (Component: typeof React.Component) => {
  class WrapComponent extends React.Component {
    render(): React.ReactNode {
      return (
        <div>
          <p>WrapComponent</p>
          <Component />
        </div>
      )
    }
  }

  return WrapComponent
}

const HOCComponent1 = HOCWithoutForwardRef(TestComponent)
const RefHOCWithoutForwardRefDemo = () => {
  const logger = createLoggerWithScope('RefHOCWithoutForwardRefDemo')
  const wrapRef = useRef(null)

  useEffect(() => {
    // wrapRef 指向的是 WrapComponent 實(shí)例 而不是 HOCComponent1 實(shí)例
    logger.log(wrapRef.current)
  }, [])

  return <HOCComponent1 ref={wrapRef} />
}

React中的ref怎么使用

如果我們希望 ref 指向的是被包裹的 TestComponent 而不是 HOC 內(nèi)部的 WrapComponent 時(shí)該怎么辦呢?

這時(shí)候就可以用 forwardRef 進(jìn)行轉(zhuǎn)發(fā)了

/** @description HOC 中使用 forwardRef 轉(zhuǎn)發(fā) ref */
const HOCWithForwardRef = (Component: typeof React.Component) => {
  class WrapComponent extends React.Component<{
    forwardedRef: LegacyRef<any>
  }> {
    render(): React.ReactNode {
      const { forwardedRef } = this.props

      return (
        <div>
          <p>WrapComponent</p>
          <Component ref={forwardedRef} />
        </div>
      )
    }
  }

  return React.forwardRef((props, ref) => (
    <WrapComponent forwardedRef={ref} {...props} />
  ))
}

const HOCComponent2 = HOCWithForwardRef(TestComponent)
const RefHOCWithForwardRefDemo = () => {
  const logger = createLoggerWithScope('RefHOCWithForwardRefDemo')
  const hocComponent2Ref = useRef(null)

  useEffect(() => {
    // hocComponent2Ref 指向的是 HOCComponent2 實(shí)例
    logger.log(hocComponent2Ref.current)
  }, [])

  return <HOCComponent2 ref={hocComponent2Ref} />
}

React中的ref怎么使用

2.2. ref 實(shí)現(xiàn)組件通信

一般我們可以通過父組件改變子組件 props 的方式觸發(fā)子組件的更新渲染完成組件間通信

但如果我們不希望通過這種改變子組件 props 的方式的話還能有別的辦法嗎?

可以通過 ref 獲取子組件實(shí)例,然后子組件暴露出通信的方法,父組件調(diào)用該方法即可觸發(fā)子組件的更新渲染

對于函數(shù)組件,由于其不存在組件實(shí)例這樣的說法,但我們可以通過 useImperativeHandle 這個(gè) hook 來指定 ref 引用時(shí)得到的屬性和方法,下面我們分別用類組件和函數(shù)組件都實(shí)現(xiàn)一遍

2.2.1. 類組件 ref 暴露組件實(shí)例

/**
 * 父 -> 子 使用 ref
 * 子 -> 父 使用 props 回調(diào)
 */
class CommunicationDemoFather extends React.Component<
  {},
  CommunicationDemoFatherState
> {
  state: Readonly<CommunicationDemoFatherState> = {
    fatherToChildMessage: '',
    childToFatherMessage: '',
  }

  childRef = React.createRef<CommunicationDemoChild>()

  /** @description 提供給子組件修改父組件中的狀態(tài) */
  handleChildToFather = (message: string) => {
    this.setState((state) => ({
      ...state,
      childToFatherMessage: message,
    }))
  }

  constructor(props: {}) {
    super(props)
    this.handleChildToFather = this.handleChildToFather.bind(this)
  }

  render(): React.ReactNode {
    const { fatherToChildMessage, childToFatherMessage } = this.state

    return (
      <div className={s.father}>
        <h4>父組件</h4>
        <p>子組件對我說:{childToFatherMessage}</p>
        <div className={s.messageInputBox}>
          <section>
            <label htmlFor="to-father">我對子組件說:</label>
            <input
              type="text"
              id="to-child"
              onChange={(e) =>
                this.setState((state) => ({
                  ...state,
                  fatherToChildMessage: e.target.value,
                }))
              }
            />
          </section>

          {/* 父 -> 子 -- 使用 ref 完成組件通信 */}
          <button
            onClick={() =>
              this.childRef.current?.setFatherToChildMessage(
                fatherToChildMessage,
              )
            }
          >
            發(fā)送
          </button>
        </div>

        <CommunicationDemoChild
          ref={this.childRef}
          onChildToFather={this.handleChildToFather}
        />
      </div>
    )
  }
}

interface CommunicationDemoChildProps {
  onChildToFather: (message: string) => void
}
// 子組件自己維護(hù)狀態(tài) 不依賴于父組件 props
interface CommunicationDemoChildState {
  fatherToChildMessage: string
  childToFatherMessage: string
}
class CommunicationDemoChild extends React.Component<
  CommunicationDemoChildProps,
  CommunicationDemoChildState
> {
  state: Readonly<CommunicationDemoChildState> = {
    fatherToChildMessage: '',
    childToFatherMessage: '',
  }

  /** @description 暴露給父組件使用的 API -- 修改父到子的消息 fatherToChildMessage */
  setFatherToChildMessage(message: string) {
    this.setState((state) => ({ ...state, fatherToChildMessage: message }))
  }

  render(): React.ReactNode {
    const { onChildToFather: emitChildToFather } = this.props
    const { fatherToChildMessage, childToFatherMessage } = this.state

    return (
      <div className={s.child}>
        <h4>子組件</h4>
        <p>父組件對我說:{fatherToChildMessage}</p>
        <div className={s.messageInputBox}>
          <section>
            <label htmlFor="to-father">我對父組件說:</label>
            <input
              type="text"
              id="to-father"
              onChange={(e) =>
                this.setState((state) => ({
                  ...state,
                  childToFatherMessage: e.target.value,
                }))
              }
            />
          </section>

          {/* 子 -> 父 -- 使用 props 回調(diào)完成組件通信 */}
          <button onClick={() => emitChildToFather(childToFatherMessage)}>
            發(fā)送
          </button>
        </div>
      </div>
    )
  }
}

React中的ref怎么使用

2.2.2. 函數(shù)組件 ref 暴露指定方法

使用 useImperativeHandle hook 可以讓我們指定 ref 引用時(shí)能獲取到的屬性和方法,個(gè)人認(rèn)為相比類組件的 ref,使用這種方式能夠更加好的控制組件想暴露給外界的 API

而不像類組件那樣直接全部暴露出去,當(dāng)然,如果你想在類組件中只暴露部分 API 的話,可以用前面說的合并轉(zhuǎn)發(fā)自定義 ref 的方式去完成

接下來我們就用 useImperativeHandle hook 改造上面的類組件實(shí)現(xiàn)的 demo 吧

interface ChildRef {
  setFatherToChildMessage: (message: string) => void
}

/**
 * 父 -> 子 使用 ref
 * 子 -> 父 使用 props 回調(diào)
 */
const CommunicationDemoFunctionComponentFather: React.FC = () => {
  const [fatherToChildMessage, setFatherToChildMessage] = useState('')
  const [childToFatherMessage, setChildToFatherMessage] = useState('')

  const childRef = useRef<ChildRef>(null)

  return (
    <div className={s.father}>
      <h4>父組件</h4>
      <p>子組件對我說:{childToFatherMessage}</p>
      <div className={s.messageInputBox}>
        <section>
          <label htmlFor="to-father">我對子組件說:</label>
          <input
            type="text"
            id="to-child"
            onChange={(e) => setFatherToChildMessage(e.target.value)}
          />
        </section>

        {/* 父 -> 子 -- 使用 ref 完成組件通信 */}
        <button
          onClick={() =>
            childRef.current?.setFatherToChildMessage(fatherToChildMessage)
          }
        >
          發(fā)送
        </button>
      </div>

      <CommunicationDemoFunctionComponentChild
        ref={childRef}
        onChildToFather={(message) => setChildToFatherMessage(message)}
      />
    </div>
  )
}

interface CommunicationDemoFunctionComponentChildProps {
  onChildToFather: (message: string) => void
}
const CommunicationDemoFunctionComponentChild = forwardRef<
  ChildRef,
  CommunicationDemoFunctionComponentChildProps
>((props, ref) => {
  const { onChildToFather: emitChildToFather } = props

  // 子組件自己維護(hù)狀態(tài) 不依賴于父組件 props
  const [fatherToChildMessage, setFatherToChildMessage] = useState('')
  const [childToFatherMessage, setChildToFatherMessage] = useState('')

  // 定義暴露給外界的 API
  useImperativeHandle(ref, () => ({ setFatherToChildMessage }))

  return (
    <div className={s.child}>
      <h4>子組件</h4>
      <p>父組件對我說:{fatherToChildMessage}</p>
      <div className={s.messageInputBox}>
        <section>
          <label htmlFor="to-father">我對父組件說:</label>
          <input
            type="text"
            id="to-father"
            onChange={(e) => setChildToFatherMessage(e.target.value)}
          />
        </section>

        {/* 子 -> 父 -- 使用 props 回調(diào)完成組件通信 */}
        <button onClick={() => emitChildToFather(childToFatherMessage)}>
          發(fā)送
        </button>
      </div>
    </div>
  )
})

2.3. 函數(shù)組件緩存數(shù)據(jù)

當(dāng)我們在函數(shù)組件中如果數(shù)據(jù)更新后不希望視圖改變,也就是說視圖不依賴于這個(gè)數(shù)據(jù),這個(gè)時(shí)候可以考慮用 useRef 對這種數(shù)據(jù)進(jìn)行緩存

為什么 useRef 可以對數(shù)據(jù)進(jìn)行緩存?

還記得之前說的 useRef 在函數(shù)組件中的作用原理嗎?

React 會(huì)將 useRef 和函數(shù)組件對應(yīng)的 fiber 對象關(guān)聯(lián),將 useRef 創(chuàng)建的 ref 對象掛載到對應(yīng)的 fiber 對象上,這樣一來每次函數(shù)組件執(zhí)行,只要函數(shù)組件不被銷毀,那么對應(yīng)的 fiber 對象實(shí)例也會(huì)一直存在,所以 ref 也能夠被保留下來

利用這個(gè)特性,我們可以將數(shù)據(jù)放到 useRef 中,由于它在內(nèi)存中一直都是同一塊內(nèi)存地址,所以無論如何變化都不會(huì)影響到視圖的改變

:::warning{title=注意}

一定要看清前提,只適用于與視圖無關(guān)的數(shù)據(jù)

:::

我們通過一個(gè)簡單的 demo 來更清楚地體會(huì)下這個(gè)應(yīng)用場景

假設(shè)我有一個(gè) todoList 列表,視圖上會(huì)把這個(gè)列表渲染出來,并且有一個(gè)數(shù)據(jù) activeTodoItem 是控制當(dāng)前選中的是哪個(gè) todoItem

點(diǎn)擊 todoItem 會(huì)切換這個(gè) activeTodoItem,但是并不需要在視圖上作出任何變化,如果使用 useState 去保存 activeTodoItem,那么當(dāng)其變化時(shí)會(huì)導(dǎo)致函數(shù)組件重新執(zhí)行,視圖重新渲染,但在這個(gè)場景中我們并不希望更新視圖

相對的,我們希望這個(gè) activeTodoItem 數(shù)據(jù)被緩存起來,不會(huì)隨著視圖的重新渲染而導(dǎo)致其作為 useState 的執(zhí)行結(jié)果重新生成一遍,因此我們可以改成用 useRef 實(shí)現(xiàn),因?yàn)槠湓趦?nèi)存中一直都是同一塊內(nèi)存地址,這樣就不會(huì)因?yàn)樗母淖兌乱晥D了

同理,在 useEffect 中如果使用到了 useRef 的數(shù)據(jù),也不需要將其聲明到 deps 數(shù)組中,因?yàn)槠鋬?nèi)存地址不會(huì)變化,所以每次在 useEffect 中獲取到的 ref 數(shù)據(jù)一定是最新的

interface TodoItem {
  id: number
  name: string
}

const todoList: TodoItem[] = [
  {
    id: 1,
    name: 'coding',
  },
  {
    id: 2,
    name: 'eating',
  },
  {
    id: 3,
    name: 'sleeping',
  },
  {
    id: 4,
    name: 'playing',
  },
]

const CacheDataWithRefDemo: React.FC = () => {
  const activeTodoItem = useRef(todoList[0])

  // 模擬 componentDidUpdate -- 如果改變 activeTodoItem 后組件沒重新渲染,說明視圖可以不依賴于 activeTodoItem 數(shù)據(jù)
  useEffect(() => {
    logger.log('檢測組件是否有更新')
  })

  return (
    <div className={s.container}>
      <div className={s.list}>
        {todoList.map((todoItem) => (
          <div
            key={todoItem.id}
            className={s.item}
            onClick={() => (activeTodoItem.current = todoItem)}
          >
            <p>{todoItem.name}</p>
          </div>
        ))}
      </div>

      <button onClick={() => logger.log(activeTodoItem.current)}>
        控制臺(tái)輸出最新的 activeTodoItem
      </button>
    </div>
  )
}

React中的ref怎么使用

3. 通過 callback ref 探究 ref 原理

首先先看一個(gè)關(guān)于 callback ref 的小 Demo 來引出我們后續(xù)的內(nèi)容

interface RefDemo8State {
  counter: number
}
class RefDemo8 extends React.Component<{}, RefDemo8State> {
  state: Readonly<RefDemo8State> = {
    counter: 0,
  }

  el: HTMLDivElement | null = null

  render(): React.ReactNode {
    return (
      <div>
        <div
          ref={(el) => {
            this.el = el
            console.log('this.el -- ', this.el)
          }}
        >
          ref element
        </div>
        <button
          onClick={() => this.setState({ counter: this.state.counter + 1 })}
        >
          add
        </button>
      </div>
    )
  }
}

React中的ref怎么使用

為什么會(huì)執(zhí)行兩次?為什么第一次 this.el === null?為什么第二次又正常了?

3.1. ref 的底層原理

還記得 React 底層是有 render 階段和 commit 階段的嗎?關(guān)于 ref 的處理邏輯就在 commit 階段進(jìn)行的

React 底層有兩個(gè)關(guān)于 ref 的處理函數(shù) -- commitDetachRefcommitAttachRef

上面的 Demo 中 callback ref 執(zhí)行了兩次正是對應(yīng)著這兩次函數(shù)的調(diào)用,大致來講可以理解為 commitDetachRef 在 DOM 更新之前執(zhí)行,commitAttachRef 在 DOM 更新之后執(zhí)行

這也就不難理解為什么會(huì)有上面 Demo 中的現(xiàn)象了,但我們還是要結(jié)合源碼來看看,加深自己的理解

3.1.1. commitDetachRef

在新版本的 React 源碼中它改名為了 safelyDetachRef,但是核心邏輯沒變,這里我將核心邏輯簡化出來供大家閱讀:

packages/react-reconciler/src/ReactFiberCommitWork.js

function commitDetachRef(current: Fiber) {
  // current 是已經(jīng)調(diào)和完了的 fiber 對象
  const currentRef = current.ref

  if (currentRef !== null) {
    if (typeof currentRef === 'function') {
      // callback ref 和 string ref 執(zhí)行時(shí)機(jī)
      currentRef(null)
    } else {
      // object ref 處理時(shí)機(jī)
      currentRef.current = null
    }
  }
}

可以看到,就是從 fiber 中取出 ref,然后根據(jù) callback ref、string ref、object ref 的情況進(jìn)行處理

并且也能看到 commitDetachRef 主要是將 ref 置為 null,這也就是為什么 RefDemo8 中第一次執(zhí)行的 callback ref 中看到的 this.el 是 null 了

3.1.2. commitAttachRef

核心邏輯代碼如下:

function commitAttachRef(finishedWork: Fiber) {
  const ref = finishedWork.ref
  if (ref !== null) {
    const instance = finishedWork.stateNode
    let instanceToUse

    // 處理 ref 來源
    switch (finishedWork.tag) {
      // HostComponent 代表 DOM 元素類型的 tag
      case HostComponent:
        instanceToUse = getPublicInstance(instance)
        break

      // 類組件使用組件實(shí)例
      default:
        instanceToUse = instance
    }

    if (typeof ref === 'function') {
      // callback ref 和 string ref
      ref(instanceToUse)
    } else {
      // object ref
      ref.current = instanceToUse
    }
  }
}

3.2. 為什么 string ref 也是以函數(shù)的方式調(diào)用?

從上面的核心源碼中能看到,對于 callback refstring ref,都是統(tǒng)一以函數(shù)的方式調(diào)用,將 nullinstanceToUse 傳入

callback ref 這樣做還能理解,但是為什么 string ref 也是這樣處理呢?

因?yàn)楫?dāng) React 檢測到是 string ref 時(shí),會(huì)自動(dòng)綁定一個(gè)函數(shù)用于處理 string ref,核心源碼邏輯如下:

packages/react-reconciler/src/ReactChildFiber.js

// 從元素上獲取 ref
const mixedRef = element.ref
const stringRef = '' + mixedRef
const ref = function (value) {
  // resolvedInst 就是組件實(shí)例
  const refs = resolvedInst.refs

  if (value === null) {
    delete refs[stringRef]
  } else {
    refs[stringRef] = value
  }
}

這樣一來 string ref 也變成了一個(gè)函數(shù)了,從而可以在 commitDetachRefcommitAttachRef 中被執(zhí)行,并且也能印證為什么 string ref 會(huì)在類組件實(shí)例的 refs 屬性中獲取到

3.3. ref 的執(zhí)行時(shí)機(jī)

為什么在 RefDemo8 中我們每次點(diǎn)擊按鈕時(shí)都會(huì)觸發(fā) commitDetachRefcommitAttachRef 呢?這就需要聊聊 ref 的執(zhí)行時(shí)機(jī)了,而從上文也能夠了解到,ref 底層實(shí)際上是由 commitDetachRefcommitAttachRef 在處理核心邏輯

那么我們就得來看看這兩個(gè)函數(shù)的執(zhí)行時(shí)機(jī)才能行

3.3.1. commitDetachRef 執(zhí)行時(shí)機(jī)

packages/react-reconciler/src/ReactFiberCommitWork.js

function commitMutationEffectsOnFiber(
  finishedWork: Fiber,
  root: FiberRoot,
  lanes: Lanes,
) {
  const current = finishedWork.alternate
  const flags = finishedWork.flags

  if (flags & Ref) {
    if (current !== null) {
      // 也就是 commitDetachRef
      safelyDetachRef(current, current.return)
    }
  }
}

3.3.2. commitAttachRef 執(zhí)行時(shí)機(jī)

packages/react-reconciler/src/ReactFiberCommitWork.js

function commitLayoutEffectOnFiber(
  finishedRoot: FiberRoot,
  current: Fiber | null,
  finishedWork: Fiber,
  committedLanes: Lanes,
) {
  const flags = finishedWork.flags

  if (flags & Ref) {
    safelyAttachRef(finishedWork, finishedWork.return)
  }
}

3.3.3. fiber 何時(shí)打上 Ref tag?

可以看到,只有當(dāng) fiber 被打上了 Ref 這個(gè) flag tag 時(shí)才會(huì)去執(zhí)行 commitDetachRef/commitAttachRef

那么什么時(shí)候會(huì)標(biāo)記 Ref tag 呢?

packages/react-reconciler/src/ReactFiberBeginWork.js

function markRef(current: Fiber | null, workInProgress: Fiber) {
  const ref = workInProgress.ref

  if (
    // current === null 意味著是初次掛載,fiber 首次調(diào)和時(shí)會(huì)打上 Ref tag
    (current === null && ref !== null) ||
    // current !== null 意味著是更新,此時(shí)需要 ref 發(fā)生了變化才會(huì)打上 Ref tag
    (current !== null && current.ref !== ref)
  ) {
    // Schedule a Ref effect
    workInProgress.flags |= Ref
  }
}

3.3.4. 為什么每次點(diǎn)擊按鈕 callback ref 都會(huì)執(zhí)行?

那么現(xiàn)在再回過頭來思考 RefDemo8 中為什么每次點(diǎn)擊按鈕都會(huì)執(zhí)行 commitDetachRefcommitAttachRef 呢?

注意我們使用 callback ref 的時(shí)候是如何使用的

<div
  ref={(el) => {
    this.el = el
    console.log('this.el -- ', this.el)
  }}
>
  ref element
</div>

是直接聲明了一個(gè)箭頭函數(shù),這樣的方式會(huì)導(dǎo)致每次渲染這個(gè) div 元素時(shí),給 ref 賦值的都是一個(gè)新的箭頭函數(shù),盡管函數(shù)的內(nèi)容是一樣的,但內(nèi)存地址不同,因而 current.ref !== ref 這個(gè)判斷條件會(huì)成立,從而每次都會(huì)觸發(fā)更新

3.3.5. 如何解決?

那么要如何解決這個(gè)問題呢?既然我們已經(jīng)知道了問題的原因,那么就好說了,只要讓每次賦值給 ref 的函數(shù)都是同一個(gè)就可以了唄~

const logger = createLoggerWithScope('RefDemo9')

interface RefDemo9Props {}
interface RefDemo9State {
  counter: number
}
class RefDemo9 extends React.Component<RefDemo9Props, RefDemo9State> {
  state: Readonly<RefDemo9State> = {
    counter: 0,
  }

  el: HTMLDivElement | null = null

  constructor(props: RefDemo9Props) {
    super(props)
    this.setElRef = this.setElRef.bind(this)
  }

  setElRef(el: HTMLDivElement | null) {
    this.el = el
    logger.log('this.el -- ', this.el)
  }

  render(): React.ReactNode {
    return (
      <div>
        <div ref={this.setElRef}>ref element</div>
        <button
          onClick={() => this.setState({ counter: this.state.counter + 1 })}
        >
          add
        </button>
      </div>
    )
  }
}

React中的ref怎么使用

關(guān)于“React中的ref怎么使用”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí),可以關(guān)注億速云行業(yè)資訊頻道,小編每天都會(huì)為大家更新不同的知識(shí)點(diǎn)。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI