如何解决在组件重新渲染上,输入文件的值不起作用
我在React Component中将受控输入与类型文件一起使用。如果我在输入组件中选择一个文件并切换主要组件的显示/隐藏行为。在重新渲染组件时,输入不起作用,并抛出以下错误:
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.
const [filePath,setPath] = useState('');
<input
key={"a"}
id={"1"}
name={"file input"}
type="file"
value={filePath}
multiple
onChange={(event) =>
setPath(event.target.value)
}
/>
解决方法
您指的是获取文件名的错误
您应该使用event.target.files[0]
尝试使用
onChange={(event) => setPath(event.target.files[0].name)}
,如果要将状态字符串const [filePath,setPath] = useState('');
的默认值设置为空字符串
然后这也应该工作
value={filePath}
另外,您可能需要考虑使用defaultValue
道具
您的语法问题
更改
value={filePath | ''}
到
value={filePath || ''}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。