簡體   English   中英

如何在 useEffect 中向 useRef 添加事件偵聽器

[英]How to add an event listener to useRef in useEffect

我正在構建一個自定義鈎子,我想在其中向 ref 添加一個事件偵聽器,但我不確定如何正確清理,因為listReflistRef.current可能為空:

export const myHook: MyHook = () => {
  const listRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    // I can check for the presence of `listRef.current` here ...
    if (listRef && listRef.current) {
      listRef.current.addEventListener(...)
    }

    // ... but what's the right way for the return function?
    return listRef.current.removeEventListener(...)
  })

  return [listRef]
}

編輯:

但是我也必須檢查返回函數中是否存在listRef ,對嗎?

是的,您可以做的是將所有內容都包裹在 if 語句中

  useEffect(() => {
    // Everything around if statement
    if (listRef && listRef.current) {
      listRef.current.addEventListener(...)

      return () => {
        listRef.current.removeEventListener(...)
      }
    }
  })

如果你不調用addEventListener ,你就不需要調用removeEventListener ,所以這就是你把所有東西都放在if


您需要在 return 中傳遞一個函數,該函數執行您在清理中想要執行的操作。

export const myHook: MyHook = () => {
  const listRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    // This is ok
    if (listRef && listRef.current) {
      listRef.current.addEventListener(...)
    }

    // Passing a function that calls your function
    return () => {
        listRef.current.removeEventListener(...)
    }
  })

  return [listRef]
}

您需要注意的另一件事是在fooEventListener內部, ...應該是函數的相同引用,這意味着:

你不應該這樣做:

  useEffect(() => {
    if (listRef && listRef.current) {
      listRef.current.addEventListener(() => console.log('do something'))
    }

    return () => {
        listRef.current.removeEventListener(() => console.log('do something'))
    }
  })

你應該這樣做:

  useEffect(() => {
    const myFunction = () => console.log('do something')

    if (listRef && listRef.current) {
      // Passing the same reference
      listRef.current.addEventListener(myFunction)
    }

    return () => {
      // Passing the same reference
      listRef.current.removeEventListener(myFunction)
    }
  })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM