在多个输入元素中使用单个 ref 对象

Use a single ref object across multiple input elements

我有一个包含多个输入元素的表单。我想在父组件中访问这些输入的值。为此,我可以使用 state,但目前我正在探索 refs 的使用。我知道可以这样记录输入的值(以便 inputRef 对象随着输入值的变化而更新)

const inputRef = useRef()

return(
  <input id = "example" ref = {inputRef} />
);

我想知道是否可以在多个输入中使用相同的 ref 对象,例如 inputRef.current 是一个使用输入 ID 作为键的对象。

例如:

inputRef = useRef()

return(
  <>
    <input id = "fname" ref = {"set inputRef.current.fname"} />
    <input id = "lname" ref = {"set inputRef.current.lname"} />
    <input id = "email" ref = {"set inputRef.current.email"} />
  </>
);

这种方法可以避免创建多个 ref 对象的冗长操作。

inputRef = useRef()

<input id = "fname" ref = {ref => inputRef.current.fname = ref} />
<input id = "lname" ref = {ref => inputRef.current.lname = ref} />
<input id = "email" ref = {ref => inputRef.current.email = ref} />