react dropzone:防止内部元素显示文件选择器



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

基本上,我有以下元素:

  • 一个应该允许
    • 拖放,以及
    • 本机文件选择器on click
  • 不显示本机文件选择器on click的内部按钮

我现在遇到的问题是,当单击内部按钮时,阻止本机文件选择器出现。

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

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()是一种方法,但我已经读到,由于许多原因(来源1,来源2(,应该避免使用它。我尝试在内部按钮中使用noClick: true,但它不起作用——很可能是因为它无法停止父级的<input>标记。

除了使用stopPropagation之外,还有其他方法可以尝试吗?

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

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

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

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

最新更新