代码拉取完成,页面将自动刷新
import React from 'react';
import { getImg } from '../../../tool/file';
import Transition from '../../transition';
import style from './style.module.less';
// 动态加载
const Zmage = React.lazy(() => import('react-zmage'));
interface IProps {
src: string;
className?: string;
preview?: boolean;
[key: string]: any;
}
interface IState {
src: string;
err: boolean;
imgStyle: React.CSSProperties;
previewStyle: React.CSSProperties;
}
export default class Img extends React.Component<IProps, IState> {
box?: HTMLDivElement | null;
state = {
src: '',
err: false,
imgStyle: {},
previewStyle: {},
};
componentDidMount() {
this.load();
}
// 图片加载后显示出最短边
load = async () => {
try {
this.setState({ err: false });
const { src, width, height } = await getImg(this.props.src);
const box = this.box!;
const widthRatio = width / (box.clientWidth || width);
const heightRatio = height / (box.clientHeight || height);
const ratio = widthRatio > heightRatio;
const imgRatio = ratio ? heightRatio : widthRatio;
const previewRatio = !ratio ? heightRatio : widthRatio;
this.setState({
src,
imgStyle: {
width: width / imgRatio,
height: height / imgRatio,
},
previewStyle: {
width: width / previewRatio,
height: height / previewRatio,
},
});
} catch (e) {
this.setState({ err: true });
}
};
render() {
const { src, className, preview, ...props } = this.props;
const { err, imgStyle, previewStyle, ...state } = this.state;
let main: JSX.Element = <div key="loading" className={`fill center loading ${style.loading}`} />;
if (err) {
main = (
<div key="err" className={`fill center ${style.err}`}>
<span onClick={this.load}>重新加载</span>
</div>
);
} else if (state.src) {
main = (
<>
<img key="img" style={imgStyle} className={preview ? style.preview : undefined} {...state} />
{preview && (
<div key="preview" className="fill center">
<React.Suspense fallback={<div className="loading" />}>
<Zmage radius={0} style={previewStyle} {...state} />
</React.Suspense>
</div>
)}
</>
);
}
return (
<div className={`center ${style.box} ${className}`} ref={box => (this.box = box)} {...props}>
<Transition name="fade">{main}</Transition>
</div>
);
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。