当一个元素失去焦点时,我正在尝试触发一个函数,但是似乎在我的React应用程序中无法识别模糊事件。我不清楚我缺少什么。以下代码段恰好位于我组件内的return方法上方。
我的div带有参考{infoWindow}。目前,当我在div窗口中单击然后再单击时,console.log不会输出任何内容。
const infoWindow = useRef<HTMLDivElement>(null);
if (infoWindow.current) {
infoWindow.current.addEventListener('blur', (event) => {
console.log(`We've been blurred`);
});
}
答案 0 :(得分:1)
这不是在React中引入副作用的方法,向元素添加事件侦听器是一种副作用,应该在useEffect内创建副作用。
这是您的代码有问题
const infoWindow = useRef<HTMLDivElement>(null);
// assume your component gets rendered once - at the initial render the component is not mounted in dom yet
// then infoWindow.current is null, and an event listener will not be added. This is what is probably happening with you.
// assume your component is rendered 1000 times, then you will add 999 event listeners, which is definitely not what you want
if (infoWindow.current) {
infoWindow.current.addEventListener('blur', (event) => {
console.log(`We've been blurred`);
});
}
解决方案是使用useEffect
useEffect(() => {
if (infoWindow.current) {
const handler = (event) => {
console.log(`We've been blurred`);
}
// notice that i get a reference to the element here, so i can safely use it in the clean function
const element = infoWindow.current
element.addEventListener('blur', handler);
// this is a clean function that will be called to clear the side effects you just introduced
return () => element.removeEventListener('blur', handler);
}
}, [])
编辑 上面提到的是正确的,但是您还有另一个问题,默认情况下div元素不接收焦点事件,因此不会模糊。如果您想让某个元素模糊并聚焦,请向其添加tabIndex,以便在div上执行
<div tabIndex={0}>...</div>
答案 1 :(得分:0)
为什么不只将一个onBlur
事件监听器添加到div?
https://reactjs.org/docs/accessibility.html#mouse-and-pointer-events