1.新增一个子组件文件:ToBase64Img.js
import React, { Component } from 'react';
import { Modal } from 'antd';
import fetch from 'dva/fetch';
import { object2formdata } from '@/utils/utils';
import domain from '@/utils/domain-config';
class ToBase64Img extends React.Component {
state = {
visible: false,
bigImg: '',
base64Path: '',
pathCache: {}
};
handleImgEnlarge(imgPath) {
this.setState({
bigImg: imgPath,
visible: true
})
};
handleOk () {
this.setState({
bigImg: '',
visible: false
})
}
handleOpenImg(img) {
window.open(img);
}
async getImg(urlStr) {
const { base64Path, pathCache } = this.state;
if (base64Path && pathCache[urlStr] && pathCache[urlStr] == base64Path) return
if (pathCache[urlStr]) {
this.setState({
base64Path: pathCache[urlStr]
})
return
}
let url = `${domain}/manage/img/admin/getImg`
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
credentials: 'include',
mode:'cors',
cache:'default',
body: `urlStr=${urlStr}`
}).then((res) => res.json()).then((res) => {
pathCache[urlStr] = `data:image/png;base64,${res.data}`
this.setState({
base64Path: `data:image/png;base64,${res.data}`,
pathCache
})
})
}
render() {
const { imgPath } = this.props
const { bigImg, base64Path } = this.state
this.getImg(imgPath)
return (
<div>
<img
src={base64Path}
style={{ height: '70px', marginRight: '10px' }}
onClick={() => this.handleImgEnlarge(imgPath)}
/>
<Modal
title="查看图片"
visible={this.state.visible}
onCancel={this.handleOk.bind(this)}
onOk={this.handleOk.bind(this)}
style={{ position: 'relative' }}
>
<div style={{ width: '400px', marginLeft: '35px' }}>
<img src={bigImg} style={{ width: '400px' }} onClick={() => this.handleOpenImg(bigImg)} />
</div>
</Modal>
</div>
)
}
}
export default ToBase64Img;
2.在父组件引入
import ToBase64Img from '@/components/ToBase64Img';
3.调用
<ToBase64Img imgPath={img} {...this.props} />