forked from osdio/noder-react-native
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCustomImage.js
More file actions
128 lines (120 loc) · 2.64 KB
/
CustomImage.js
File metadata and controls
128 lines (120 loc) · 2.64 KB
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
import React, {
Component
} from 'react'
import {
Image,
View,
StyleSheet,
Text,
TouchableOpacity
} from 'react-native'
import PropTypes from 'prop-types'
import Icon from 'react-native-vector-icons/Ionicons'
import PureRenderMixin from 'react-addons-pure-render-mixin'
export default class CustomImage extends Component {
static propTypes = {
defaultSize: PropTypes.object,
maxImageWidth: PropTypes.number,
uri: PropTypes.string
};
static defaultProps = {
defaultSize: {
height: 200,
width: 200
}
};
constructor (props) {
super(props)
this.state = {
size: props.defaultSize,
isLoaded: false,
error: false
}
this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this)
this._loadImg(props.uri, props.maxImageWidth)
}
_loadImg (uri, maxImageWidth) {
if (!uri) { return }
const startTime = new Date().getTime()
Image.getSize(uri, (w, h) => {
if (w >= maxImageWidth) {
h = (maxImageWidth / w) * h
w = maxImageWidth
}
let leftTime = 500 - (new Date().getTime() - startTime)
if (leftTime > 0) {
setTimeout(() => {
this.setState({
size: {
width: w,
height: h
},
isLoaded: true
})
}, leftTime)
} else {
this.setState({
size: {
width: w,
height: h
},
isLoaded: true
})
}
}, () => {
this.setState({
error: true
})
})
}
render () {
const {uri, style} = this.props
const {size, isLoaded, error} = this.state
if (isLoaded) {
return (
<Image
source={{uri}}
style={[style, size]}
/>
)
}
if (error) {
return (
<TouchableOpacity onPress={() => this._loadImg(this.props.uri, this.props.maxImageWidth)}>
<View style={[styles.container, size]}>
<Icon
name='ios-image-outline'
size={60}
style={styles.icon}
/>
<Text>
点击重新加载图片
</Text>
</View>
</TouchableOpacity>
)
}
return (
<View style={[styles.container, size]}>
<Icon
name='ios-image-outline'
size={60}
style={styles.icon}
/>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'rgba(0,0,0,0.05)',
borderRadius: 5,
margin: 10
},
icon: {
color: 'rgba(0,0,0,0.5)'
}
})