-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathBadge.js
107 lines (95 loc) · 2.69 KB
/
Badge.js
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
/*
* A smart badge for react-native apps
* https://github.com/react-native-component/react-native-smart-badge/
* Released under the MIT license
* Copyright (c) 2016 react-native-component <[email protected]>
*/
import React, {
Component,
PropTypes,
} from 'react'
import {
View,
Text,
StyleSheet,
} from 'react-native'
const styles = StyleSheet.create({
container: {
backgroundColor: 'red',
justifyContent: 'center',
alignItems: 'center',
flexDirection: 'row',
},
text: {
paddingVertical: 2,
paddingHorizontal: 4,
color: '#fff',
fontFamily: '.HelveticaNeueInterface-MediumP4',
backgroundColor: 'transparent',
fontSize: 14,
textAlign: 'center', //for android
textAlignVertical: 'center', //for android
},
})
export default class Badge extends Component {
static defaultProps = {
extraPaddingHorizontal: 10,
minHeight: 0,
minWidth: 0,
}
static propTypes = {
//borderRadius: PropTypes.number, //number 18, null 5
extraPaddingHorizontal: PropTypes.number,
style: View.propTypes.style,
textStyle: Text.propTypes.style,
minHeight: PropTypes.number,
minWidth: PropTypes.number,
}
// 构造
constructor (props) {
super(props)
// 初始状态
this.state = {}
this._width = 0
}
render () {
return (
<View ref={ component => this._container = component } style={[styles.container, this.props.style]}>
{this._renderChildren()}
</View>
)
}
_renderChildren () {
return React.Children.map(this.props.children, (child) => {
if (!React.isValidElement(child)) {
return (
<Text onLayout={this._onLayout} style={[styles.text, this.props.textStyle]}>{child}</Text>
)
}
return child
})
}
_onLayout = (e) => {
let width
if (e.nativeEvent.layout.width <= e.nativeEvent.layout.height) {
width = e.nativeEvent.layout.height
}
else {
width = e.nativeEvent.layout.width + this.props.extraPaddingHorizontal
}
width = Math.max(width, this.props.minWidth)
if (this._width == width) {
return
}
this._width = width
let height = Math.max(e.nativeEvent.layout.height, this.props.minHeight)
let borderRadius = height / 2
this._container.setNativeProps({
style: {
width,
height,
borderRadius,
},
});
}
}