如何在useEffect中将事件侦听器添加到useRef



我正在构建一个自定义挂钩,我想在其中向ref添加一个事件侦听器,但我不确定如何正确清理,因为listReflistRef.current可能为null:

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(...)
}
}
}, [listRef])

如果不调用addEventListener,就不需要调用removeEventListener,所以这就是为什么要将所有内容都放在if中。


您需要在返回中传递一个函数,该函数可以执行您想在清理中执行的操作。

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(...)
}
}, [listRef])
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)
}
}, [listRef])

最新更新