ref.current.focus() 为空

发布于 01-17 04:40 字数 469 浏览 2 评论 0原文

我有一个图标和一个输入字段。当单击图标时,我需要关注输入。

代码:

const inputRef = useRef(null)

图标:

<ChatIcon className="btn" onClick={inputRef.current.focus()} />

输入:

  <input
    placeholder="add a comment..."
    type="text"
    value={comment}
    ref={inputRef}
    onChange={(e) => setComment(e.target.value)}
  />

错误:

类型错误:无法读取 null 的属性(读取“焦点”)

I have a icon and a input field. While onclick on icon i need to focus on the input.

Code:

const inputRef = useRef(null)

Icon:

<ChatIcon className="btn" onClick={inputRef.current.focus()} />

Input:

  <input
    placeholder="add a comment..."
    type="text"
    value={comment}
    ref={inputRef}
    onChange={(e) => setComment(e.target.value)}
  />

Error:

TypeError: Cannot read properties of null (reading 'focus')

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

岁月打碎记忆2025-01-24 04:40:41

您在单击之前调用该函数,您需要像这样添加它

<ChatIcon className="btn" onClick={inputRef.current.focus} />

,或者如果您想更安全

<ChatIcon className="btn" onClick={() => inputRef.current && inputRef.current.focus()} />

You are calling the function before its click you need to add it like this

<ChatIcon className="btn" onClick={inputRef.current.focus} />

or if you wanna be safer

<ChatIcon className="btn" onClick={() => inputRef.current && inputRef.current.focus()} />
旧伤还要旧人安2025-01-24 04:40:41

onClick 调用您传入的参数的返回值。就是这样

onClick calls the return value of the argument you passed in. That's what it is

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文