How to reset ReactJS file input

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

I have file upload input:


And I handle upload t

10条回答
  •  天命终不由人
    2020-12-29 01:52

    Here is my solution using redux form

    class FileInput extends React.Component {
      constructor() {
        super();
    
        this.deleteImage = this.deleteImage.bind(this);
      }
    
      deleteImage() {
        // Just setting input ref value to null did not work well with redux form
        // At the same time just calling on change with nothing didn't do the trick
        // just using onChange does the change in redux form but if you try selecting
        // the same image again it doesn't show in the preview cause the onChange of the
        // input is not called since for the input the value is not changing
        // but for redux form would be.
    
        this.fileInput.value = null;
        this.props.input.onChange();
      }
    
      render() {
        const { input: { onChange, value }, accept, disabled, error } = this.props;
        const { edited } = this.state;
    
        return (
          
    {/* ref and on change are key properties here */} onChange(e.target.files[0])} multiple={false} accept={accept} capture ref={(input) => { this.fileInput = input; }} disabled={disabled} /> {!value ? {/* Add button */}
    {error &&
    {error}
    }
}
); } } FileInput.propTypes = { input: object.isRequired, accept: string, disabled: bool, error: string }; FileInput.defaultProps = { accept: '*', }; export default FileInput;

提交回复
热议问题