如何清除 Material UI 文件类型的文本字段
How to clear a Material UI textfield of file type
我尝试了多种方法,但我似乎无法使用 type="file"
清除 Material UI 文本字段
我正在限制文件大小,如果用户超出限制,会弹出错误消息,但文本字段也需要清除。
这是我的代码:
function CreateClaim(props) {
const [supporting_docs, setSupportingDocs] = useState(null);
const handleFileUpload = (event) => {
event.preventDefault()
if(event.target.files[0].size > 10971520) {
setFileError(true)
setSupportingDocs(null)
}
else {
setSupportingDocs(event.target.files)
}
};
return (
<TextField onChange={handleFileUpload}
InputLabelProps={{ shrink: true }}
margin="normal"
required
fullWidth
id="supporting_docs"
label="Bewys van uitgawe"
name="supporting_docs"
type="file"
/>
)
} export default CreateClaim
错误消息效果很好,但无法清除文本字段,有什么建议吗?
您可以添加这一行:
if (event.target.files[0].size > 10971520) {
setFileError(true);
setSupportingDocs(null);
e.target.value = null;
}
你可以试试这个。如果文件超过 1MB,它将显示错误。
Click to see preview
const Demo = () => {
const [error, setError] = useState(false);
const handleFileUpload = (e) => {
console.log(e.target.files[0]);
const file = e.target.files[0];
if(file.size) return setError(true)
}
return(<>
{error ? <h1 style={{color: 'red'}} >Error</h1> : <TextField
onChange={handleFileUpload}
InputLabelProps={{ shrink: true }}
margin="normal"
required
fullWidth
id="supporting_docs"
label="Bewys van uitgawe"
name="supporting_docs"
type="file"
/>}
</>)
}
我尝试了多种方法,但我似乎无法使用 type="file"
我正在限制文件大小,如果用户超出限制,会弹出错误消息,但文本字段也需要清除。
这是我的代码:
function CreateClaim(props) {
const [supporting_docs, setSupportingDocs] = useState(null);
const handleFileUpload = (event) => {
event.preventDefault()
if(event.target.files[0].size > 10971520) {
setFileError(true)
setSupportingDocs(null)
}
else {
setSupportingDocs(event.target.files)
}
};
return (
<TextField onChange={handleFileUpload}
InputLabelProps={{ shrink: true }}
margin="normal"
required
fullWidth
id="supporting_docs"
label="Bewys van uitgawe"
name="supporting_docs"
type="file"
/>
)
} export default CreateClaim
错误消息效果很好,但无法清除文本字段,有什么建议吗?
您可以添加这一行:
if (event.target.files[0].size > 10971520) {
setFileError(true);
setSupportingDocs(null);
e.target.value = null;
}
你可以试试这个。如果文件超过 1MB,它将显示错误。 Click to see preview
const Demo = () => {
const [error, setError] = useState(false);
const handleFileUpload = (e) => {
console.log(e.target.files[0]);
const file = e.target.files[0];
if(file.size) return setError(true)
}
return(<>
{error ? <h1 style={{color: 'red'}} >Error</h1> : <TextField
onChange={handleFileUpload}
InputLabelProps={{ shrink: true }}
margin="normal"
required
fullWidth
id="supporting_docs"
label="Bewys van uitgawe"
name="supporting_docs"
type="file"
/>}
</>)
}