【发布时间】: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 1、source 2)。我尝试在内部按钮中使用 noClick: true,但它不起作用 - 很可能是因为它无法停止父级的 <input> 标记。
除了使用stopPropagation之外,我还应该尝试其他方法吗?
【问题讨论】: