setFocus 在对话框组件中与 react-hook-form 不起作用。

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

setFocus not working with react-hook-form in a dialog component

问题

我在使用react-hook-form的setFocus函数时遇到了问题。我尝试在打开SignInDialog组件时聚焦到一个输入字段(用户名),但没有成功。我尝试了几种方法,包括使用useEffect在打开对话框时调用setFocus,以及将ref属性传递给底层的输入元素,但似乎都不起作用。

这是一个重现问题的代码沙盒链接:https://codesandbox.io/p/sandbox/signindialog-smhpmx?file=%2Fsrc%2FSignInDialog.jsx%3A10%2C14

有人可以帮助我找出问题出在哪里吗?

英文:

I’m having an issue with react-hook-form’s setFocus function. I’m trying to focus an input field (username) in a SignInDialog component when the dialog is opened, but it’s not working. I’ve tried several approaches, including using useEffect to call setFocus when the dialog is opened and forwarding the ref prop to the underlying input element, but nothing seems to work.

Here’s a link to a code sandbox that reproduces the issue: https://codesandbox.io/p/sandbox/signindialog-smhpmx?file=%2Fsrc%2FSignInDialog.jsx%3A10%2C14

Can anyone help me figure out what’s going wrong?

答案1

得分: 0

你的效果钩子立即运行,因为你的 SignInDialog 组件始终被挂载/渲染,但焦点调用无法聚焦到任何东西,因为输入框还没有出现。

你可以向依赖项添加另一个标志,例如:

  useEffect(() => {
    if (openSignInDialog) {
      // 仅添加setTimeout也无效
      setTimeout(() => {
        setFocus("username");
      });
    }
  }, [setFocus, openSignInDialog]);

但更简单的方法是将 autoFocus 属性直接传递给你的 TextFieldStyled

英文:

Your effect hook runs immediately because your SignInDialog component is always mounted/rendered, but the focus call can't focus anything because the input is not there yet.

You can either add another flag to the deps, for example:

  useEffect(() => {
    if (openSignInDialog) {
      // It also does not work without timeout
      setTimeout(() => {
        setFocus("username");
      });
    }
  }, [setFocus, openSignInDialog]);

But the easier way would be to just pass autoFocus props to your TextFieldStyled.

huangapple
  • 本文由 发表于 2023年7月14日 04:05:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76682897.html
匿名

发表评论

匿名网友

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

确定