如何使用 React hooks 设置文件对象的状态?

2023-12-28

我想添加到从输入类型文件获取的状态和文件对象,我的问题是我无法用此更新状态:

currentTarget.files[0]

我收到此错误:

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

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

用于获取数据的 HandleChange 事件

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从输入字段并将其发送到后端


看起来您正在尝试将 'value' 属性传递给文件输入。

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

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

您应该像使用文件一样使用文件输入uncontrolled component

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


Solution:从文件输入设置状态值(如果确实需要),但不要从状态设置输入值。只需找到另一种方式来显示该文件已在 UI 中选择即可。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 React hooks 设置文件对象的状态? 的相关文章

随机推荐