我有一个正在保存的 react 组件
const inputSchemaVersionRef =useRef<HTMLInputElement>();
组件有多个文本字段,ref
连接到每个文本字段,如下所示:
inputRef={(ref) => (inputSchemaVersionRef.current = ref)}
(它是 inputRef
因为 MUI 库)。这有效。
当我尝试 inputRef={inputSchemaVersionRef}
时,引用已连接到文本字段的最后一个实例。
有人可以解释为什么它只引用最后一个文本字段以及为什么我需要将引用分配给当前的 inputSchemaVersionRef 才能使其工作?
最佳答案
useRef
返回一个 ref 对象,其中单个 current
属性最初设置为您提供的初始值(您可以在 react documentation 中查看)。这就是它的工作原理。当要更改 ref 值时,需要更改 current
属性以将 ref 对象引用保留在内存中。
至于inputRef
问题;这是因为您有多个文本字段(如您所说),并且引用连接到每个文本字段,因此从逻辑上讲,该值会被每个文本字段一一替换,直到到达最后一个并存储在裁判。如果您想防止这种情况,可以将 inputSchemaVersionRef
初始化为一个空数组,如下所示(我假设您有两个文本字段):
const inputSchemaVersionRef =useRef<HTMLInputElement[]>([]);
并将文本字段连接到引用,如下所示:
<TextField
id="myFirstTextField"
inputRef={ref => {
inputSchemaVersionRef.current[0] = ref
}}
/>
<TextField
id="mySecondTextField"
inputRef={ref => {
inputSchemaVersionRef.current[1] = ref
}}
/>
或者您可以将 inputSchemaVersionRef
初始化为 json,如下所示:
const inputSchemaVersionRef = useRef<{
myFirstTextField:HTMLInputElement | null;
mySecondTextField:HTMLInputElement | null
}>({myFirstTextField:null, mySecondTextField: null});
然后像下面这样使用它:
<TextField
id="myFirstTextField"
inputRef={ref => {
inputSchemaVersionRef.current.myFirstTextField = ref
}}
/>
<TextField
id="mySecondTextField"
inputRef={ref => {
inputSchemaVersionRef.current.mySecondTextField = ref
}}
/>
因此输入引用值永远不会被覆盖。
关于reactjs - 对多个元素使用一个 useRef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74773139/