英文:
useRef doesn't focus on modal
问题
我有一个模态框(弹出窗口),里面是一个相册。我尝试使用useRef钩子来聚焦在div上,但它不像我期望的那样工作。我试图创建一个函数,使我能够通过按键盘箭头切换图像。它几乎完成了。但是现在,要切换图像,我必须点击整个模态框才能使其聚焦。没有这个,键盘不会切换图像。
我找到了这段代码来自动聚焦在模态DIV上,但它不起作用。
const ref = useRef(null);
useEffect(() => {
ref.current.focus();
}, []);
return (
<div
ref={ref}
tabIndex={1}
onKeyDown={(e) => handleKeyboardArrows(e)}>
<h1>My Popup</h1>
</div>
);
请帮我解释我的错误并帮助我。谢谢!
英文:
I have a modal (popup) which sort of gallery. I'm trying to focus on the div by using useRef hook but it doen't work as I expacted. I'm trying to create function that give me ability to switch images by pressing keyboard arrows. And it's almost done. But now for switching images I've to click on whole modal for focusing on it. Without this keyboard doesn't switch the images.
I found this code for auto focusing on modal DIV but it's not work.
const ref = useRef(null);
useEffect(() => {
ref.current.focus();
}, []);
return(
<div
ref={ref}
tabIndex={1}
onKeyDown={(e) => handleKeyboardArrows(e)}>
<h1>My Popup</h1>
</div>
);
Guess someone explaing my mistakes and help me. Thx
答案1
得分: 1
useEffect
钩子与空的依赖数组一起使用时,将只在组件挂载时运行一次,而不会在模态框打开或关闭时运行。在你的代码中,焦点方法只会被调用一次,如果在那个时候模态框不可见或未渲染,它可能不起作用。为了解决这个问题,你需要使用一个反映模态框状态或属性的依赖,比如 modalOpen
。
useEffect(() => {
if (modalOpen) {
modalRef.current.focus();
}
}, [modalOpen]);
英文:
useEffect
hook with an empty dependency array will only run once when the component mounts, not when the modal is opened or closed. In your code, the focus method will only be called once, and it may not work if the modal is not visible or rendered at that time. To fix this, you need to use a dependency that reflects the modal state or props, such as modalOpen
.
useEffect(() => {
if (modalOpen) {
modalRef.current.focus();
}
}, [modalOpen]);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论