How to reset ReactJS file input

后端 未结 10 1062
傲寒
傲寒 2020-12-29 00:55

I have file upload input:


And I handle upload t

10条回答
  •  孤独总比滥情好
    2020-12-29 01:40

    The following worked for me using React Hooks. This is done using what is known as a "controlled input". That means, the inputs are controlled by state, or their source of truth is state.

    TL;DR Resetting the file input was a two-step process using both the useState() and useRef() hooks.

    NOTE: I also included how I reset a text input in case anyone else was curious.

    function CreatePost({ user }) {
        const [content, setContent] = React.useState("");
        const [image, setImage] = React.useState(null); //See Supporting Documentation #1
        const imageInputRef = React.useRef(); //See Supporting Documentation #2
    
        function handleSubmit(event) {
            event.preventDefault(); //Stop the pesky default reload function
            setContent(""); //Resets the value of the first input - See #1
    
            //////START of File Input Reset
            imageInputRef.current.value = "";//Resets the file name of the file input - See #2
            setImage(null); //Resets the value of the file input - See #1
            //////END of File Input Reset
        }
    
        return (
        
    setContent(event.target.value)} value={content} //Make this input's value, controlled by state /> setImage(event.target.files[0])} //See Supporting Doc #3 ref={imageInputRef} //Apply the ref to the input, now it's controlled - See #2 />
    ) };

    Supporting Documentation:

    1. useState Hook
      • Returns a stateful value, and a function to update it.
    2. useRef Hook
      • If you pass a ref object to React, React will set its current property to the corresponding DOM node whenever that node changes.
    3. Using files from web apps
      • If the user selects just one file, it is then only necessary to consider the first file of the list.

提交回复
热议问题