如何使用React挂钩将文件对象设置为状态? [英] How to set file object in state with React hooks?

查看:90
本文介绍了如何使用React挂钩将文件对象设置为状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想添加从输入类型文件中获取的状态和文件对象,我的问题是我无法使用以下命令更新状态:

I want to add to state and file object which I'm getting from input type file, and my problem is that I cannot update state with this:

currentTarget.files[0]

我收到此错误:

DOMException:无法在'HTMLInputElement'上设置'value'属性:此输入元素接受文件名,该文件名只能以编程方式设置为空字符串.

DOMException: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string.

const [data, changeData] = useState({
  name: '',
  surname: '',
  cv: '',
});

用于获取数据的HandleChangeEvent

HandleChangeEvent for getting data

const handleChangeData = ({ currentTarget }, key) => {
    if (currentTarget.type === 'file') {
      const files = currentTarget.files[0];
      changeData((prevState) => {
        console.log(prevState);
        return { ...prevState, [key]: files };
      });
    } else {
      // Validate property
      const val = currentTarget.value;
      const errorMessage = validateProperty(currentTarget);
      if (errorMessage) errors[currentTarget.name] = errorMessage;
      else delete errors[currentTarget.name];

      changeData((prevState) => {
        return { ...prevState, [key]: val };
      });
    }
  };

我想从输入字段中获取属性files并将其发送到后端

I want to get property files from input field and send it to backend

推荐答案

您似乎正在尝试将值"属性传递给文件输入.

It looks like you are trying to pass a 'value' prop to the file input.

<input type="file" value="???" />

React(以及在html/js中)文件输入值只能由用户设置,而不能以编程方式设置(由于安全原因).

In React (as well as in html/js) file inputs values can only be set by a user, and not programmatically (due to security reasons).

您应该像使用uncontrolled component

https://reactjs.org/docs/uncontrol -components.html#the-file-input-tag

解决方案:从文件输入中设置状态值(如果确实需要),但不要从状态中设置输入值.只需找到另一种方法来表明该文件已在用户界面中被选中即可.

Solution: Set the state's value from the file input (if you really need it), but don't set the input's value from state. Just find another way to show that the file has already been chosen in UI.

这篇关于如何使用React挂钩将文件对象设置为状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆