【问题标题】:react-dropzone onDrop firing twicereact-dropzone onDrop 发射两次
【发布时间】:2018-02-04 16:59:00
【问题描述】:

所以我尝试向我的 React + Redux 应用程序添加一个非常简单的文件上传,我发现 Dropzone 是最方便的方式。这是我的设置。

我有一个FileInput 组件

import React from 'react'
import Dropzone from 'react-dropzone'

class FileInput extends React.Component {
    constructor(props) {
        super(props);
        this.onChange = this.onChange.bind(this);
    }

    onChange(files) {
        // For Redux form
        if (this.props.input) {
            const {input: {onChange}} = this.props;
            onChange(files[0])
        }
        else if(this.props.onChange){
            this.props.onChange(files[0])
        }
        else{
            console.warn('redux-form-dropzone => Forgot to pass onChange props ?');
        }
    }

    render() {
        return (
            <Dropzone onDrop={ this.onChange } {...this.props} >
                Drag&Drop the image <br/> or click to select one
            </Dropzone>
        )
    }
}
export default FileInput

我在页面上这样使用它:

<FileInput
    onChange={(file) => console.log('dropped', file)}
    className='add-avatar-dropzone'
    activeClassName='dropzone-active'
/>

(用于调试目的的console.log)

但是当我尝试删除文件时,我得到 2 个日志输出。第一个是我删除的文件,第二个是某种代理,可能由 react 本身提供...

我想知道如何摆脱那个代理,为什么它首先要这样做?

我尝试过的事情

我试图消除几个明显的问题点,但似乎没有做出任何改变。

  1. onChange 函数重命名为handleDrop 之类的其他名称并将其重写为handleDrop = (files) =&gt; {
  2. 删除构造函数(给自己赋值似乎很奇怪)

【问题讨论】:

    标签: reactjs proxy react-dropzone


    【解决方案1】:

    结果很简单,没想到我真的很傻。

    上面代码中的onChange 属性传递给Dropzone,然后传递给输入字段,这就是混乱的根源。

    我将代码修改为这样工作:

    render() {
    
        const { onChange, ...rest } = this.props
    
        return (
            <Dropzone onDrop={ this.onChange } {...rest} >
                Drag&Drop the image <br/> or click to select one
            </Dropzone>
        )
    }
    

    效果很好

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-15
      • 2020-11-08
      • 2014-02-26
      • 2018-09-05
      • 1970-01-01
      • 1970-01-01
      • 2018-10-16
      • 2015-11-30
      相关资源
      最近更新 更多