How to reset ReactJS file input

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

I have file upload input:


And I handle upload t

10条回答
  •  感情败类
    2020-12-29 01:40

    I know file input is always uncontrolled however the following code still works in my own porject, I can reset the input with no problems at all.

    constructor(props) {
        super(props);
        this.state = {
            selectedFile: undefined,
            selectedFileName: undefined,
            imageSrc: undefined,
            value: ''
        };
    
        this.handleChange = this.handleChange.bind(this);
        this.removeImage = this.removeImage.bind(this);
    }
    
    handleChange(event) {
        if (event.target.files[0]) {
            this.setState({
                selectedFile: event.target.files[0],
                selectedFileName: event.target.files[0].name,
                imageSrc: window.URL.createObjectURL(event.target.files[0]),
                value: event.target.value,
            });
        }
    }
    
    // Call this function to reset input
    removeImage() {
        this.setState({
            selectedFile: undefined,
            selectedFileName: undefined,
            imageSrc: undefined,
            value: ''
        })
    }
    
    render() {
        return (
            
        );
    }
    

提交回复
热议问题