useRef 不关注模态框。

huangapple go评论91阅读模式
英文:

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(() =&gt; {
  ref.current.focus();
}, []);

return(
  &lt;div 
      ref={ref} 
      tabIndex={1} 
      onKeyDown={(e) =&gt; handleKeyboardArrows(e)}&gt;
          
          &lt;h1&gt;My Popup&lt;/h1&gt;
  &lt;/div&gt;
);

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(() =&gt; {
  if (modalOpen) {
    modalRef.current.focus();
  }
}, [modalOpen]);

huangapple
  • 本文由 发表于 2023年7月10日 15:26:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76651555.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定