reactjs - 如何使用 SpeedDial 上传文件?
问题描述
(这似乎以前被问过,但我找不到任何关于它是否真的被回答的提示)
MUI 有一个很好的演示来创建上传按钮,归结为:
<input accept="image/*" className={classes.input} id="icon-button-file" type="file" />
<label htmlFor="icon-button-file">
<IconButton color="primary" aria-label="upload picture" component="span">
<PhotoCamera />
</IconButton>
</label>
我想知道如何使用Speed Dial来实现相同的功能。本质上 theSpeedDialAction
似乎具体化为 a <button/>
,但是不可能将 a 包裹SpeedDialAction
在 a<label htmlFor />
中,因为它的父级会尝试在其上设置一些道具并且会失败。
那么,我一般如何从快速拨号或 FAB 中启动文件选择呢?
解决方案
这是 - 据我所知 - 不可能以任何方式添加 htmlFor。所以我要做的是添加一个隐藏的输入类型文件,然后向它添加一个引用。然后在SpeedDialAction按钮的 onclick 中,我将调用一个处理函数来单击输入参考。像这样:
const inputRef = useRef();
const handleFileUploadClick = () => {
inputRef.current.click();
};
然后你的 SpeedDialAction:
<SpeedDialAction
onClick={handleFileUploadClick}
... the rest of your props
/>
然后最后你的实际输入:
<input
style={{ display: "none" }}
ref={inputRef}
accept="image/*"
id="contained-button-file"
multiple
type="file"
/>
工作演示:https ://codesandbox.io/s/material-demo-forked-f9i6q?file=/demo.tsx:1691-1868
推荐阅读
- html - 如何显示来自用户输入的超链接?
- reactjs - 从 API ReactJs 获取数组数组
- angular - 如何仅获取ngrx选择器中更改的值?
- matlab - 如何添加先前请求的时间函数作为 ODE 45 中的输入?[MATLAB]
- python - ValueError: 目标尺寸 (torch.Size([32])) 必须与输入尺寸 (torch.Size([32, 3])) 相同
- linux - 如何获取世界上所有时区的 POSIX 时区字符串
- python - 缺少 1 个必需的位置参数:part5() 错误
- amazon-web-services - AWS 从 Lambda 向 Sagemaker 发送图像:如何设置内容处理?
- regex - 输入电子邮件地址时正则表达式检查有效的总字符数
- python - openpyxl中通过填充域填充单元格背景的速度