Skip to content

Commit

Permalink
update md
Browse files Browse the repository at this point in the history
  • Loading branch information
chilijung committed Apr 11, 2018
1 parent cf14522 commit ecfa1c8
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ class Demo extends React.Component {
| onError | (err: Event) => void | null | This function will be called when image is failed |
| loading | () => React.Element<*> | null | Return a React element that will show when image is loading |
| error | () => React.Element<*> | null | Return a React element that will show when image is crashed |
| image | ({src: string}) => React.Element<*> | null | Final result will render to this customized React element, if you don't assign this props default image will render into `<img src={src}/>` |
| image | ({src: string, width: number, height: number}) => React.Element<*> | null | Final result will render to this customized React element, if you don't assign this props default image will render into `<img src={src} width={width} height={height}/>` |

## Start example server

Expand Down
15 changes: 12 additions & 3 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ type State = {
isLoading: boolean,
isError: boolean,
src: ?string,
width: ?number,
height: ?number,
errMsg: ?any,
}

Expand All @@ -26,6 +28,8 @@ export default class ImageLoader extends React.Component<Props, State> {
isLoading: true,
isError: false,
src: null,
width: null,
height: null,
errMsg: null
}
}
Expand All @@ -48,10 +52,13 @@ export default class ImageLoader extends React.Component<Props, State> {
});

const image = new Image();

image.src = props.src;
image.onload = () => {
this.setState({
src: image.src,
width: image.width,
height: image.height,
isLoading: false,
isError: false,
errMsg: null
Expand All @@ -63,6 +70,8 @@ export default class ImageLoader extends React.Component<Props, State> {
image.onerror = (err) => {
this.setState({
src: null,
width: null,
height: null,
isLoading: false,
isError: true,
errMsg: err
Expand All @@ -75,16 +84,16 @@ export default class ImageLoader extends React.Component<Props, State> {

render() {
const {loading, error, image} = this.props;
const {src, isLoading, isError, errMsg} = this.state;
const {src, width, height, isLoading, isError, errMsg} = this.state;

if (loading && isLoading) {
return loading();
} else if (error && isError && errMsg) {
return error(errMsg);
} else if (src && image) {
return image({src});
return image({src, width, height});
} else if (src) {
return <img {...this.props} src={src}/>
return <img {...this.props} src={src} width={width} height={height}/>
}

return null;
Expand Down

0 comments on commit ecfa1c8

Please sign in to comment.