6 Star 27 Fork 6

dyb881 / react to typescript

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
index.tsx 2.53 KB
一键复制 编辑 原始数据 按行查看 历史
dyb881 提交于 2019-03-01 15:16 . 添加代码审查
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>
);
}
}
TypeScript
1
https://gitee.com/dyb881/react-ts.git
git@gitee.com:dyb881/react-ts.git
dyb881
react-ts
react to typescript
master

搜索帮助