【问题标题】:React function not working from child component反应功能不适用于子组件
【发布时间】:2017-11-07 15:30:43
【问题描述】:

我正在尝试使一个功能正常工作,该功能可以删除使用 React Dropzone 和 react-sortable 上传的图像。

我的 dropzone 工作正常,排序工作正常,但由于某种原因,我在可排序项目上从数组中删除该特定项目的功能不起作用。 onClick 事件似乎没有调用该函数。

我的代码如下。

 const SortableItem = SortableElement(({value, sortIndex, onRemove}) =>
      <li>{value.name} <a onClick={() => onRemove(sortIndex)}>Remove {value.name}</a></li>
    );

 const SortableList = SortableContainer(({items, onRemove}) => {
    return (
    <ul>
      {items.map((image, index) => (
        <SortableItem key={`item-${index}`} index={index} value={image} sortIndex={index} onRemove={onRemove} />
      ))}
    </ul>
  );
});

class renderDropzoneInput extends React.Component {

constructor (props) {
    super(props)
    this.state = { files: [] }
    this.handleDrop = this.handleDrop.bind(this)
  }

  handleDrop (files) {
    this.setState({
      files
    });
    this.props.input.onChange(files)
  }

  remove (index){
    var array = this.state.files
    array.splice(index, 1)
    this.setState({files: array })
    this.props.input.onChange(array)
  }

  onSortEnd = ({oldIndex, newIndex}) => {
    this.setState({
      files: arrayMove(this.state.files, oldIndex, newIndex),
    });
  };

  render () {
    const {
        input, placeholder,
        meta: {touched, error}
      } = this.props

    return (
      <div>
        <Dropzone
          {...input}
          name={input.name}
          onDrop={this.handleDrop}
        >
          <div>Drop your images here or click to open file picker</div>
        </Dropzone>
        {touched && error && <span>{error}</span>}


        <SortableList items={this.state.files} onSortEnd={this.onSortEnd} onRemove={(index) => this.remove(index)} />

      </div>
    );
  }
}
export default renderDropzoneInput

【问题讨论】:

    标签: reactjs react-dropzone react-sortable-hoc


    【解决方案1】:

    更新:这是由 react-sortable-hoc 吞下点击事件引起的。在元素上设置 pressDelay 属性可以触发点击功能。

    【讨论】:

      【解决方案2】:

      这是一个老问题,但像我这样仍然看到这个问题的人可能想读一下:https://github.com/clauderic/react-sortable-hoc/issues/111#issuecomment-272746004

      问题在于,正如 Matt 发现的那样,可排序的临时性会吞噬 onClick 事件。但我们可以通过设置pressDelaydistance 来解决问题。

      对我来说,最好的选择是为可排序列表设置最小距离,效果很好

      您还可以使用 distance 属性设置在触发排序之前要拖动的最小距离(例如,您可以设置 1px 的距离,如下所示:distance={1})

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-07
        • 1970-01-01
        • 2019-12-22
        • 2019-11-27
        • 1970-01-01
        相关资源
        最近更新 更多