如何修复在';HTMLInputElement';上为Reaction设置';Value';属性失败? [英] How to fix Failed to set the 'value' property on 'HTMLInputElement' for react?
本文介绍了如何修复在';HTMLInputElement';上为Reaction设置';Value';属性失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在处理Nextjs,并尝试上载单个文件。每次附加新文件时,我都会在控制台日志中收到此错误。
在控制台,我看到此错误:
Warning: A component is changing an uncontrolled input of type file to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.
然后,第二个是:
react-dom.development.js:2592 Uncaught 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.
以下是我的示例代码:
- 呈现函数处的HTML路径
<div className="form-group">
<label htmlFor="p_file">Image</label>
<input
id="p_file"
type="file"
className="form-control-file"
value={formData.image}
onChange={ e => onChangeImage(e)} />
</div>
- Javascript路径
const [formData, setFormData] = useState({
...,
image: undefined
});
const onChangeImage = event => {
console.log(event.target.files[0]);
setFormData( prev => ({
...prev,
image: event.target.files[0]
}));
}
推荐答案
来自React documentation非受控元素:
在Reaction中,
<input type="file" />
始终是不受控制的组件,因为它的值只能由用户设置,而不能以编程方式设置。
这是一项安全功能,可确保您在没有用户明确选择的情况下无法从用户磁盘拉取数据。
在我看来,这似乎不是您要做的事情。您要做的就是显示所选文件的名称。您可以通过使用隐藏的file元素创建自己的标签和按钮来做到这一点。单击自定义按钮时,必须调用HTMLFileInput上的单击事件。在文件输入上注册您的更改事件,并使用响应更新您的自定义元素。
这篇关于如何修复在';HTMLInputElement';上为Reaction设置';Value';属性失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文