简体   繁体   English

如何使用React挂钩将文件对象设置为状态?

[英]How to set file object in state with React hooks?

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]

I'm getting this error: 我收到此错误:

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

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

HandleChangeEvent for getting data HandleChangeEvent用于获取数据

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 };
      });
    }
  };

I want to get property files from input field and send it to backend 我想从输入字段获取属性files并将其发送到后端

It looks like you are trying to pass a 'value' prop to the file input. 似乎您正在尝试将“值”属性传递给文件输入。

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

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). React (以及html/js )中,文件输入值只能由用户设置,而不能以编程方式设置(由于安全原因)。

You should work with your file input as with an uncontrolled component 您应该将文件输入与uncontrolled component

https://reactjs.org/docs/uncontrolled-components.html#the-file-input-tag 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. 只是找到另一种方式来表明该文件已在UI中被选中。

@chumakoff answer provide a good solution, but it worth noting, this has nothing to do with react. @chumakoff答案提供了一个很好的解决方案,但值得注意的是,这与反应无关。 It is how the browser works. 这是浏览器的工作方式。

You added only part of your code, so I assume you are trying to create a hook for setting value and change handler, just like you'll do with the default <input type="text"/> . 您仅添加了部分代码,因此我假设您正在尝试创建一个用于设置值和更改处理程序的钩子,就像使用默认的<input type="text"/>

However, <input type="file"/> work differently - only the user can set it's value (ei the file object and the file name ) for security reasons. 但是, <input type="file"/>工作方式有所不同-出于安全原因,只有用户可以设置其值(即file objectfile name )。 As the error suggest, the only thing you can set this value to is - an empty string. 如错误提示所示,您可以将此值设置为唯一的-空字符串。

See this question about Angular , which produce the same error. 请参阅有关Angular的问题该问题会产生相同的错误。

changeData(
    { 
        ...data, 
        [key]: val 
    }
);

EDIT: cause of comment 编辑: 评论原因

As my grandpa say: " RTFM " 我爷爷说:“ RTFM

https://reactjs.org/docs/hooks-state.html https://reactjs.org/docs/hooks-state.html

I don't want to copy paste the doc 我不想复制粘贴文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM