【问题标题】:react-dropzone: prevent inner element from showing file pickerreact-dropzone:防止内部元素显示文件选择器
【发布时间】:2020-09-27 16:57:40
【问题描述】:

我目前正在使用react-dropzone 插件,遇到了一个文档中没有准确描述的用例。

基本上,我有以下元素:

  • 应该允许两者的外部放置区
    • 拖放和
    • 本机文件选择器on click
  • 不显示本机文件选择器的内部按钮on click

我现在遇到的问题是在单击 inner 按钮时阻止本机文件选择器显示。

为了说明我的示例,您可以将此代码粘贴到 View Code 部分。

import React from 'react';
import {useDropzone} from 'react-dropzone';

function Dropzone(props) {
  const {getRootProps, getInputProps, open, acceptedFiles} = useDropzone({
    // Disable click and keydown behavior
    noKeyboard: true
  });

  const files = acceptedFiles.map(file => (
    <li key={file.path}>
      {file.path} - {file.size} bytes
    </li>
  ));

  return (
    <div className="container">
      <div {...getRootProps({className: 'dropzone'})}>
        <input {...getInputProps()} />
        <p>Drag 'n' drop some files here</p>
        <InnerButton />
      </div>
      <aside>
        <h4>Files</h4>
        <ul>{files}</ul>
      </aside>
    </div>
  );
}

function InnerButton(props) {
  const { getRootProps } = useDropzone({ noClick: true }); // doesn't stop the parent's input file picker

  return (
    <button
      {...getRootProps({
        onClick: (event) => event.stopPropagation(), // this is bad for many reasons
      })}
      type="button">
      This button should not open the file picker
    </button>
  );
}

<Dropzone />

我认为使用event.stopPropagation() 是一种方法,但我读到应该避免使用它的原因有很多(source 1source 2)。我尝试在内部按钮中使用 noClick: true,但它不起作用 - 很可能是因为它无法停止父级的 &lt;input&gt; 标记。

除了使用stopPropagation之外,我还应该尝试其他方法吗?

【问题讨论】:

    标签: reactjs react-dropzone


    【解决方案1】:

    我得到了答案on GitHub,将其发布在这里以防其他人遇到同样的问题。

    没有办法解决它。您必须使用 stopPropagation() 来阻止事件冒泡 DOM。您的另一个选择是在父级上也使用noClick

    noClick 仅在单击 dropzone 节点时禁用打开文件选择器。它不会阻止事件冒泡。

    我们唯一能做的就是提供一个调用stopPropagation()noClickBubbling 选项,但用户已经可以这样做了。

    【讨论】:

      猜你喜欢
      • 2018-09-15
      • 2013-02-15
      • 1970-01-01
      • 1970-01-01
      • 2021-03-10
      • 1970-01-01
      • 2015-12-03
      • 2011-08-14
      • 1970-01-01
      相关资源
      最近更新 更多