UNPKG

1.7 kBJavaScriptView Raw
1import React, {
2 PropTypes,
3 ViewPropTypes,
4 Component,
5} from 'react';
6import {
7 View,
8} from 'react-native';
9
10// why not Object, See Here http://t.cn/RKQqS4n
11// !! justifyContent alignItems alignSelf 一定要照这个顺序来!,且前面的不能省略
12const FLEX_REGEXP = [
13 { key: 'flex', regexp: /\d+/ },
14 { key: 'flexDirection', regexp: /(row(?!-)|row-reverse|column(?!-)|column-reverse)/ },
15 { key: 'flexWrap', regexp: /(wrap|nowrap)/ },
16 { key: 'justifyContent', regexp: /(flex-start|flex-end|center|space-between|space-around)/ },
17 { key: 'alignItems', regexp: /(flex-start|flex-end|center|stretch)/ },
18 { key: 'alignSelf', regexp: /(auto|flex-start|flex-end|center|stretch)/ },
19];
20
21const getFlexStyle = (flexStr) => {
22 const style = {
23 flex: {},
24 };
25 for (let i = 0; i < FLEX_REGEXP.length; i++) {
26 const prop = FLEX_REGEXP[i];
27 if (prop.regexp.test(flexStr)) {
28 flexStr = flexStr.replace(prop.regexp, (match) => {
29 style.flex[prop.key] = prop.key === 'flex' ? +match : match;
30 });
31 }
32 }
33 return style;
34};
35
36class Flex extends Component {
37 static propTypes = {
38 children: PropTypes.oneOfType([PropTypes.element, PropTypes.array]),
39 flex: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
40 style: ViewPropTypes || (View.propTypes && View.propTypes.style),
41 }
42 static defaultProps = {
43 children: null,
44 flex: '1 row',
45 style: null,
46 }
47 render() {
48 const {
49 children,
50 flex,
51 style,
52 ...other
53 } = this.props;
54 const flexStyle = getFlexStyle(flex);
55 return (
56 <View style={[flexStyle.flex, style]} {...other}>
57 {children}
58 </View>
59 );
60 }
61}
62
63export default Flex;