我有一個包含許多輸入元素的表單。我想在父組件中訪問這些輸入的值。為此,我可以使用 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 物件的繁瑣。
uj5u.com熱心網友回復:
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} />
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/476453.html
