使用清除按钮清除react.useState时遇到问题
我发现很难清除我设置为 setImportFile useState 的文件输入。这是我声明的 useState
const [importFile, setImportFile] = React.useState<File | null>();
const [fileError, setFileError] = React.useState<string>("");
我在这个 const 方法中清除了两个 useState 变量,但只有一个被清除,即 setFileError。
const clearModal = () => {
setImportFile(null);
setFileError("");
};
我在此方法中使用 setImportFile
const onChangeImportFile = (e: React.ChangeEvent<HTMLInputElement>) => {
e.preventDefault();
setImportFile(e.currentTarget.files ? e.currentTarget.files[0] : null);
setSaving(true);
};
这是我的渲染,其中我使用清除按钮,只有错误会清除,但文件输入不会清除。我想清空模式中的所有内容
<Form.Control
type="file"
accept='.csv, .xls, .xlsx'
required
className="primary mb-3"
name=""
onChange={onChangeImportFile}
/>
<Button variant="secondary" onClick={clearModal} > Clear </Button>
I am finding it difficult to clear this file input that I am setting to setImportFile useState. This is the useState I declared
const [importFile, setImportFile] = React.useState<File | null>();
const [fileError, setFileError] = React.useState<string>("");
I clear two useState variables in this const method but only one gets cleared which is setFileError.
const clearModal = () => {
setImportFile(null);
setFileError("");
};
I use setImportFile in this method
const onChangeImportFile = (e: React.ChangeEvent<HTMLInputElement>) => {
e.preventDefault();
setImportFile(e.currentTarget.files ? e.currentTarget.files[0] : null);
setSaving(true);
};
This is my render in which I use the clear button and only the error would clear out but the file input will not clear out. I want to empty everything in the modal
<Form.Control
type="file"
accept='.csv, .xls, .xlsx'
required
className="primary mb-3"
name=""
onChange={onChangeImportFile}
/>
<Button variant="secondary" onClick={clearModal} > Clear </Button>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您需要将状态值传递给 Form.Control,以使其受到控制(否则它不会从状态获取其值)。
I think you need to pass the state value to the Form.Control, to make it controlled (otherwise it's not getting its value from the state).
您不需要设置
File | null
因为 SetStateAction 将被设置为未定义
。试试这个:
You don't need to set
File | null
as SetStateAction will be set toundefined
.Try this: