首页 > 解决方案 > 如何使用 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 中启动文件选择呢?

标签: reactjsmaterial-ui

解决方案


这是 - 据我所知 - 不可能以任何方式添加 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


推荐阅读