在组件重新渲染上,输入文件的值不起作用

问题描述

我在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 || ''}