单击 Raised Button Material ui 打开 "choose file" 对话框

Open "choose file" dialog box on onclick of Raised Button Material ui

我的 React 项目中有一个浮动按钮(材质 ui)。我想在单击时打开 "choose file" 对话框。我没有得到任何解决方案来做到这一点。我试过这样做但没有奏效。而且我不想使用 jquery。

</div>
            <input id="myInput" type="file" style="visibility:hidden" />
            <FloatingActionButton className="floatingButton" backgroundColor='#293C8E' onClick ="$('#myInput').click();">
                <ContentAdd />
            </FloatingActionButton>
        </div>

有人可以告诉我我到底需要做什么吗?

您可以在 <label/> 标签的帮助下完成此操作:

<label htmlFor='myInput'>
  <input id="myInput" type="file" style={{visibility: 'hidden'}} />
  <FloatingActionButton
    className="floatingButton"
    backgroundColor='#293C8E'
   >
    <ContentAdd />
   </FloatingActionButton>
</label>

基本示例(不包括如何处理所选文件):

  <div>
    <input id="myInput" type="file" ref={(ref) => this.upload = ref} style={{ display: 'none' }} />
    <FloatingActionButton
      className="floatingButton"
      backgroundColor='#293C8E'
      onClick={(e) => this.upload.click() }
      >
      <ContentAdd />
    </FloatingActionButton>
  </div>

因此,您的 FloatingActionButton 的 onClick 处理程序手动触发隐藏文件上传控件(输入类型="file")的 click() 处理程序。通过在其上放置一个 ref 回调并将该引用存储在 "this.upload" 中(也可以使用 DOM 或 jQuery 来获取对隐藏上传控件的引用,但 ref 是首选反应)

这是一个有效的 jsFiddle:https://jsfiddle.net/432yz8qg/58/

虽然我的解决方案暗示使用多个 CSS 规则,但我以比 Jeff 解决方案更 React 的方式解决了这个问题。

我使用了一个 FlatButton 属性 containerElement 设置为 "label" :

const { FlatButton, SvgIcon, MuiThemeProvider, getMuiTheme } = MaterialUI;

class Example extends React.Component {
  render() {
    const buttonStyle = {
       minWidth: '56px',
       width: '56px',
       minHeight: '56px',
       height: '56px',
       borderRadius: '28px',
     };
  
    return (
      <div>
        <FlatButton
          containerElement="label"
          backgroundColor='#293C8E'
          style={buttonStyle}
          >
          <input type="file" style={{ display: 'none' }} />
        </FlatButton>
      </div>
    );
  }
}

const App = () => (
  <MuiThemeProvider muiTheme={getMuiTheme() }>
    <Example />
  </MuiThemeProvider>
);

ReactDOM.render(
  <App />,
  document.getElementById('container')
);
<script src="https://unpkg.com/react@15.2.1/dist/react-with-addons.js"></script>
<script src="https://unpkg.com/react-dom@15.2.1/dist/react-dom.js"></script>
<script src="https://rawgit.com/nathanmarks/3f5196f5973e3ff7807f2bab4e603a37/raw/f409f3bf5902c211b358a3ebe7b6cd366da551e8/mui-umd.js"></script>
<div id="container"></div>

此处有更多详细信息: