问题描述
我想添加从输入类型文件中获取的状态和文件对象,我的问题是我无法使用以下命令更新状态:
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]
我收到此错误:
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挂钩将文件对象设置为状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!