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