【问题标题】:Is there a way to dynamically access a ref's properties in react?有没有办法在反应中动态访问 ref 的属性?
【发布时间】:2021-11-21 00:11:29
【问题描述】:

我有一个包含四个文件输入的表单。不同用途的文件的不同输入。

我为每个文件创建了一个引用。

我创建了一个引用数组。

提交时,我试图访问所有参考并获取它们的 ref.current.files[0]。

下面的示例代码:

import {useRef} from 'react';

export default function myComponent(props){

const file1 = useRef(null);
const file2 = useRef(null);
const file3 = useRef(null);
const file4 = useRef(null);

const fileRefs = [file1, file2, file3, file4];

function onSubmit(){
  let files = [];

  fileRefs.map((ref) => {
    let obj = {};
    obj.fileName = ref.current.files[0].name;
    obj.file = ref.current.files[0];
    files.push(obj)
  })
}

render(
<div className="form">

<label>File 1 </label>
<input type="file" ref={file1} />

<label>File 2 </label>
<input type="file" ref={file2} />

<label>File 3 </label>
<input type="file" ref={file3} />

<label>File 4 </label>
<input type="file" ref={file4} />

<button onClick={() => onSubmit()}>Submit</button>

</div>
)
}

错误:“TypeError:无法读取 null 的属性(正在读取'文件')”

所以,我无法以这种方式访问​​ ref 的 .current 属性。

我真的不知道如何解决这个问题,只是想拼凑一些东西。

如果有人可以帮助我动态访问 ref 的当前属性,那就太好了。

【问题讨论】:

  • 您在哪里实际上 设置任何参考current 值?什么叫onSubmit?您可以在问题中包含所有相关代码吗? stackoverflow.com/help/minimal-reproducible-example
  • 我编辑了我的代码以包含它们。我在调用函数或分配 ref 时没有问题,因此为简洁起见,我将其省略了。我很抱歉。
  • 更新了@DrewReese
  • 为什么要在函数组件中使用渲染?
  • 您是否为每个输入选择一个文件? IE。四个文件输入,四个选定文件?

标签: javascript reactjs react-hooks use-ref


【解决方案1】:

我没有在您的代码中看到任何问题,如果您为所有文件输入选择一个文件,它就可以工作。只有在没有选定文件的情况下留下任何输入时,才会出现此问题。

要解决此问题,您可以使用Optional Chaining operator 对文件对象进行空检查。

ref.current.files[0]?.name

如果ref.current.files[0] 为空或未定义,则对文件对象的访问被短路并返回未定义,否则继续访问并返回文件名。

代码:

function onSubmit() {
  const files = fileRefs.map((ref) => ({
    fileName: ref.current.files[0]?.name,
    file: ref.current.files[0],
  }));

  console.log({ files });
}

【讨论】:

    【解决方案2】:

    在您的代码中,而不是 render 使用 return,您使用了渲染功能不可用的功能组件。 检查此链接以获取有效的解决方案 https://codesandbox.io/s/wonderful-faraday-upg89?file=/src/App.js

    【讨论】:

    • 是的,我没有复制代码。我在stackoverflow上即时重写了它。那是我的错。它是在实际代码中返回的。
    猜你喜欢
    • 2022-09-22
    • 2022-08-02
    • 2022-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-18
    • 2010-09-07
    • 1970-01-01
    相关资源
    最近更新 更多