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

Ben*_*Ben 5 forms input ref reactjs use-ref

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

const inputRef = useRef()

return(
  <input id = "example" ref = {inputRef} />
);
Run Code Online (Sandbox Code Playgroud)

我想知道是否可以在多个输入中使用相同的 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"} />
  </>
);
Run Code Online (Sandbox Code Playgroud)

这种方法可以节省创建多个 ref 对象的冗长过程。

小智 8

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} />
Run Code Online (Sandbox Code Playgroud)