简体   繁体   English

如何清除文件类型的 Material UI 文本字段

[英]How to clear a Material UI textfield of file type

I've tried mutliple approaches, but I cannot seem to clear a Material UI textfield with type="file"我尝试了多种方法,但我似乎无法清除带有type="file"的 Material UI 文本字段

I am limiting the file size, and if a user oversteps the limit, an error message pops up, but the Textfield also needs to be cleared.我正在限制文件大小,如果用户超出限制,会弹出一条错误消息,但还需要清除 Textfield。

Here is my code:这是我的代码:

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

The error message works well, but cant clear the Textfield, any suggestions?错误消息效果很好,但无法清除文本字段,有什么建议吗?

You can add this line:您可以添加此行:

if (event.target.files[0].size > 10971520) {
    setFileError(true);
    setSupportingDocs(null);
    e.target.value = null;
} 

You can try this.你可以试试这个。 If the file is more than 1MB it will show an Error.如果文件超过 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"         
    />}
  </>)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM