reactJS material UI Icon button to upload file

China☆狼群 提交于 2019-12-10 15:17:09

问题


I want to know how can I open the directory to upload a file using an IconButton?

<IconButton 
  iconClassName="fa fa-plus-square" 
  onClick={(e) => e.stopPropagation()} 
  type='file'
/>

using the code below shows the icon button and another button for the upload file

<IconButton iconClassName="fa fa-plus-square" onClick={(e) => e.stopPropagation()}>
    <input type="file type='file'>
</IconButton>

回答1:


A few things:

  1. You don't need type='file' on the IconButton, just on the input

  2. IconButton does not expect its children to be anything other than an SVGIcon, so I recommend that you use a regular button

  3. I wouldn't call stopPropagation in this case

  4. You have a typo in your type prop for the input. You have type="file type='file'. It should just be type="file"

So, putting that all together:

<FlatButton label="Choose file" labelPosition="before">
  <input type="file" style={styles.exampleImageInput} />
</FlatButton>

If you still want it to be an icon rather than a button, I suspect you can do something with <input> or add it as the children to FlatButton with no label.




回答2:


You can achieve the same with IconButton using the following codes.

<IconButton onClick={() => this.fileUpload.click()}>
   <FontIcon className="material-icons" >
       add_a_photo
   </FontIcon>
  </IconButton>
<input type="file" ref={(fileUpload) => {
                    this.fileUpload = fileUpload;
                  }}
  style={{ visibility: 'hidden'}} onChange={this.groupImgUpload} />



回答3:


I think the standard way from material ui examples:


 <input accept="image/*" className={classes.input} id="icon-button-file" type="file" />
  <label htmlFor="icon-button-file">
    <IconButton color="primary" className={classes.button} component="span">
      <PhotoCamera />
    </IconButton>
  </label>



来源:https://stackoverflow.com/questions/36255352/reactjs-material-ui-icon-button-to-upload-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!