React后台管理系统-file-uploader组件

React后台管理系统-file-uploader组件

1.React文件上传组件github地址: https://github.com/SoAanyip/React-FileUpload

2.Util里边新建file-uploader文件夹,里边新建index.jsx

  1. import React from 'react';
  2. import FileUpload from './react-fileupload.jsx';
  3.  
  4. class FileUploader extends React.Component{
  5.     render(){
  6.         const options={
  7.             baseUrl :'/manage/product/upload.do',
  8.             fileFieldName : 'upload_file',
  9.             dataType : 'json',
  10.             chooseAndUpload : true,
  11.             uploadSuccess : (res) => {
  12.                 this.props.onSuccess(res.data);
  13.             },
  14.             uploadError : (err) => {
  15.                 this.props.onError(err.message || '上传图片出错啦');
  16.             }
  17.         }
  18.         return (
  19.             <FileUpload options={options}>
  20.                 <button className="btn btn-xs btn-default" ref="chooseAndUpload">请选择图片</button>
  21.             </FileUpload>
  22.         )
  23.     }
  24. }
  25. export default FileUploader;

3.在save.jsx里边使用FileUploader组件

  1. <div className="form-group">
  2.                       <label className="col-md-2 control-label">商品图片</label>
  3.                       <div className="col-md-10">
  4.                       {
  5.                             this.state.subImages.length ? this.state.subImages.map(
  6.                                   (image, index) => (
  7.                                   <div className="img-con" key={index}>
  8.                                       <img className="img" src={image.url} />
  9.                                       <i className="fa fa-close" index={index} onClick={(e) => this.onImageDelete(e)}></i>
  10.                                   </div>)
  11.                               ) : (<div>请上传图片</div>)
  12.                           }
  13.                       </div>
  14.                       <div className="col-md-offset-2 col-md-10 file-upload-con">
  15.                       <FileUploader onSuccess={(res) => this.onUploadSuccess(res)}
  16.                               onError={(errMsg) => this.onUploadError(errMsg)}/>
  17.                       </div>
  18.                   </div>

4.图片上传成功后执行nUploadSuccess函数,更新state里边subImages数据

  1. //上传图片成功
  2.   onUploadSuccess(res){
  3.       let subImages = this.state.subImages;
  4.       subImages.push(res);
  5.       this.setState({
  6.           subImages : subImages
  7.       });
  8.   }

5.删除图片

  1. // 删除图片
  2.     onImageDelete(e){
  3.        let index = parseInt(e.target.getAttribute('index')),
  4.            subImages = this.state.subImages;
  5.        subImages.splice(index, 1);
  6.        this.setState({
  7.            subImages : subImages
  8.        });
  9.    }

posted on 2020-04-16 19:45  six、hc  阅读(513)  评论(0编辑  收藏  举报

导航