useRef div 元素尽管在 useEffect 中进行了聚焦,但在页面加载时不会自动聚焦。

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

useRef div element not auto-focusing on page load despite focusing in useEffect

问题

我目前正在尝试为我的应用程序添加一些键盘事件,这些事件在按下特定的代码时触发。

这是在我的DashboardWrapper组件内完成的,它基本上只是一个样式组件,但在其中呈现任何子元素:

<div className="full-vh full-vw flex-center" ref={wrapper} onKeyDown={handleKeyboardEvents}>
  {children}
</div>

这个组件在父页面内这样呈现:

<DashboardWrapper>
  {这里的子元素}
</DashboardWrapper>

该组件使用了useRef钩子,并将其分配给一个名为wrapper的变量,如下所示:

const wrapper = useRef(null)

然后,在useEffect内部,我为它分配了一个事件侦听器,调用一个触发一些控制台日志的函数:

useEffect(() => {
  wrapper.current.focus()

  if (wrapper.current !== null) {
    console.log("Running inside of if..");
    wrapper.current.addEventListener("keydown", handleKeyboardEvents)
  }

  return wrapper.current.removeEventListener("keydown", handleKeyboardEvents)
}, [])

它还调用了'focus()',这应该在页面加载时自动聚焦到相应的div,但出于某种原因它不起作用。

供参考,这是我的handleKeyboardEvents函数:

const handleKeyboardEvents = (e: React.KeyboardEvent<HTMLDivElement>) => {
  console.log(e.code);
  console.log(e);

  if (e.ctrlKey && e.code === "KeyS") {
    console.log("control and s pressed");
  }
}

我唯一能够使键盘事件开始触发的方法是手动在不同元素之间切换,直到到达相关div。然后它才起作用。

简而言之,我想要实现的是随时触发键盘事件,除非有元素(比如输入框)处于焦点状态。

也许有更有效的方法来实现这一点,但这是我目前尝试的方法。有人有任何指针吗?

英文:

I'm currently attempting to add some keyboard events to my app, which trigger if certain codes are pressed.

This is done inside of my DashboardWrapper component, which is essentially just a styling component, but renders any children inside of it:

&lt;div className=&quot;full-vh full-vw flex-center&quot; ref={wrapper} onKeyDown={handleKeyboardEvents}&gt;
  {children}
&lt;/div&gt;

This component is rendered like this inside of a parent page:

&lt;DashboardWrapper&gt;
  { children in here} 
&lt;/DashboardWrapper&gt;

The component uses the useRef hook, and assigns it to a wrapper variable, like so:

const wrapper = useRef(null)

Then, inside of a useEffect, I assign an event listener to it, calling a function which triggers some console logs:

useEffect(() =&gt; {

        wrapper.current.focus()

        if (wrapper.current !== null) {
            console.log(&quot;Running inside of if..&quot;);
            wrapper.current.addEventListener(&quot;keydown&quot;, handleKeyboardEvents)
        }

        return wrapper.current.removeEventListener(&quot;keydown&quot;, handleKeyboardEvents)
    }, [])

It also calls 'focus()', which should auto-focus the div in question upon page load - but for whatever reason, it isn't working.

For reference, this is my handleKeyboardEvents function:

const handleKeyboardEvents = (e: React.KeyboardEvent&lt;HTMLDivElement&gt;) =&gt; {

        console.log(e.code);
        console.log(e);

        if (e.ctrlKey &amp;&amp; e.code === &quot;KeyS&quot;) {
            console.log(&quot;control and s pressed&quot;);
        }
    }

The only way I can get the keyboard events to start firing is to manually tab between the different elements, until I reach the div in question. Then it works.

What I'm trying to achieve here, in short, is to be able to trigger the keyboard events at any time, except when an element (such as an input) is in focus.

There may be a more efficient way to do this - but this is my stab at it for now.

Does anyone have any pointers?

答案1

得分: 2

请添加 tabIndex="-1"<div> 元素,以便可以对其进行焦点定位。

英文:

Consider adding tabIndex=&quot;-1&quot; to the &lt;div&gt; element so that it can be focused.

huangapple
  • 本文由 发表于 2023年4月10日 21:22:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75977519.html
匿名

发表评论

匿名网友

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

确定