ref.current.focus() 为空
我有一个图标和一个输入字段。当单击图标时,我需要关注输入。
代码:
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 技术交流群。

您在单击之前调用该函数,您需要像这样添加它
,或者如果您想更安全
You are calling the function before its click you need to add it like this
or if you wanna be safer