Files
react-native-fast-image/ReactNativeFastImageExample/src/AutoSizeExample.tsx
T

95 lines
2.2 KiB
TypeScript
Raw Normal View History

2018-09-23 18:40:18 -04:00
import React, { Component } from 'react'
import { StyleSheet, View } from 'react-native'
import withCacheBust from './withCacheBust'
import SectionFlex from './SectionFlex'
2020-03-12 02:27:37 -04:00
import FastImage, { FastImageProps } from 'react-native-fast-image'
2018-09-23 18:40:18 -04:00
import Section from './Section'
import FeatureText from './FeatureText'
const GIF_URL =
'https://cdn-images-1.medium.com/max/1600/1*-CY5bU4OqiJRox7G00sftw.gif'
2020-03-12 02:27:37 -04:00
interface AutoSizingImageProps extends FastImageProps {
onLoad?: (event: any) => void
defaultHeight?: number
width: number
style?: any
}
interface AutoSizingImageState {
height: number
width: number
}
class AutoSizingImage extends Component<
AutoSizingImageProps,
AutoSizingImageState
> {
2018-09-23 18:40:18 -04:00
state = {
height: 0,
width: 0,
}
2020-03-12 02:27:37 -04:00
onLoad = (e: any) => {
2018-09-23 18:40:18 -04:00
const {
nativeEvent: { width, height },
} = e
this.setState({ width, height })
if (this.props.onLoad) {
this.props.onLoad(e)
}
2018-09-23 18:40:18 -04:00
}
getHeight = () => {
if (!this.state.height) {
2020-03-12 02:27:37 -04:00
return this.props.defaultHeight === undefined
? 300
: this.props.defaultHeight
}
2018-09-23 18:40:18 -04:00
const ratio = this.state.height / this.state.width
const height = this.props.width * ratio
return height
}
render() {
const height = this.getHeight()
return (
<FastImage
{...this.props}
onLoad={this.onLoad}
style={[{ width: this.props.width, height }, this.props.style]}
/>
)
}
}
2020-03-12 02:27:37 -04:00
interface AutoSizeExampleProps {
onPressReload: () => void
bust: boolean
2018-09-23 18:40:18 -04:00
}
2020-03-12 02:27:37 -04:00
const AutoSizeExample = ({ onPressReload, bust }: AutoSizeExampleProps) => (
2018-09-23 18:40:18 -04:00
<View>
<Section>
<FeatureText text="• AutoSize." />
</Section>
<SectionFlex onPress={onPressReload}>
<AutoSizingImage
style={styles.image}
width={200}
source={{ uri: GIF_URL + bust }}
/>
</SectionFlex>
</View>
)
const styles = StyleSheet.create({
image: {
backgroundColor: '#ddd',
margin: 20,
flex: 0,
},
})
export default withCacheBust(AutoSizeExample)