|
| 1 | +import React, { useCallback, useMemo, useState } from 'react' |
| 2 | +import { StyleSheet, View } from 'react-native' |
| 3 | +import SectionFlex from './SectionFlex' |
| 4 | +import FastImage, { FastImageProps } from 'react-native-fast-image' |
| 5 | +import Section from './Section' |
| 6 | +import FeatureText from './FeatureText' |
| 7 | +import { useCacheBust } from './useCacheBust' |
| 8 | + |
| 9 | +const GIF_URL = |
| 10 | + 'https://cdn-images-1.medium.com/max/1600/1*-CY5bU4OqiJRox7G00sftw.gif' |
| 11 | + |
| 12 | +interface AutoSizingImageProps extends FastImageProps { |
| 13 | + onLoad?: (event: any) => void |
| 14 | + defaultHeight?: number |
| 15 | + width: number |
| 16 | + style?: any |
| 17 | +} |
| 18 | + |
| 19 | +const AutoSizingImage = (props: AutoSizingImageProps) => { |
| 20 | + const [dimensions, setDimensions] = useState({ |
| 21 | + height: 0, |
| 22 | + width: 0, |
| 23 | + }) |
| 24 | + |
| 25 | + const propsOnLoad = props.onLoad |
| 26 | + const onLoad = useCallback( |
| 27 | + (e: any) => { |
| 28 | + const { |
| 29 | + nativeEvent: { width, height }, |
| 30 | + } = e |
| 31 | + setDimensions({ width, height }) |
| 32 | + if (propsOnLoad) { |
| 33 | + propsOnLoad(e) |
| 34 | + } |
| 35 | + }, |
| 36 | + [propsOnLoad], |
| 37 | + ) |
| 38 | + |
| 39 | + const height = useMemo(() => { |
| 40 | + if (!dimensions.height) { |
| 41 | + return props.defaultHeight === undefined ? 300 : props.defaultHeight |
| 42 | + } |
| 43 | + const ratio = dimensions.height / dimensions.width |
| 44 | + return props.width * ratio |
| 45 | + }, [dimensions.height, dimensions.width, props.defaultHeight, props.width]) |
| 46 | + return ( |
| 47 | + <FastImage |
| 48 | + {...props} |
| 49 | + onLoad={onLoad} |
| 50 | + style={[{ width: props.width, height }, props.style]} |
| 51 | + /> |
| 52 | + ) |
| 53 | +} |
| 54 | + |
| 55 | +export const AutoSizeExample = () => { |
| 56 | + const { bust, url } = useCacheBust(GIF_URL) |
| 57 | + return ( |
| 58 | + <View> |
| 59 | + <Section> |
| 60 | + <FeatureText text="• AutoSize." /> |
| 61 | + </Section> |
| 62 | + <SectionFlex onPress={bust}> |
| 63 | + <AutoSizingImage |
| 64 | + style={styles.image} |
| 65 | + width={200} |
| 66 | + source={{ uri: url }} |
| 67 | + /> |
| 68 | + </SectionFlex> |
| 69 | + </View> |
| 70 | + ) |
| 71 | +} |
| 72 | + |
| 73 | +const styles = StyleSheet.create({ |
| 74 | + image: { |
| 75 | + backgroundColor: '#ddd', |
| 76 | + margin: 20, |
| 77 | + flex: 0, |
| 78 | + }, |
| 79 | +}) |
0 commit comments