ref.current.focus() 为空

ref.current.focus() is null

我有一个图标和一个输入框。当点击图标时,我需要专注于输入。

代码:

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)}
  />

错误:

TypeError: 无法读取 null 的属性(读取 'focus')

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

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

或者如果你想更安全

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

onClick 调用你传入的参数的 return 值。就是这样