UNPKG

2.73 kBJavaScriptView Raw
1import React, { Component } from 'react';
2import PropTypes from 'prop-types';
3
4import {
5 StyleSheet,
6 View,
7 processColor,
8 requireNativeComponent,
9 ViewPropTypes,
10} from 'react-native';
11
12export default class LinearGradient extends Component {
13 static propTypes = {
14 start: PropTypes.oneOfType([
15 PropTypes.arrayOf(PropTypes.number),
16 PropTypes.object,
17 ]),
18 end: PropTypes.oneOfType([
19 PropTypes.arrayOf(PropTypes.number),
20 PropTypes.object,
21 ]),
22 colors: PropTypes.arrayOf(PropTypes.string).isRequired,
23 locations: PropTypes.arrayOf(PropTypes.number),
24 ...ViewPropTypes,
25 };
26
27 render() {
28 const {
29 children,
30 colors,
31 end,
32 locations,
33 start,
34 style,
35 ...otherProps
36 } = this.props;
37
38 if (colors && locations && colors.length !== locations.length) {
39 console.warn(
40 'LinearGradient colors and locations props should be arrays of the same length'
41 );
42 }
43
44 // inherit container borderRadius until this issue is resolved:
45 // https://github.com/facebook/react-native/issues/3198
46 const flatStyle = StyleSheet.flatten(style) || {};
47 const borderRadius = flatStyle.borderRadius || 0;
48
49 // this is the format taken by:
50 // http://developer.android.com/reference/android/graphics/Path.html#addRoundRect(android.graphics.RectF, float[], android.graphics.Path.Direction)
51 const borderRadiiPerCorner = [
52 flatStyle.borderTopLeftRadius || borderRadius,
53 flatStyle.borderTopLeftRadius || borderRadius,
54 flatStyle.borderTopRightRadius || borderRadius,
55 flatStyle.borderTopRightRadius || borderRadius,
56 flatStyle.borderBottomRightRadius || borderRadius,
57 flatStyle.borderBottomRightRadius || borderRadius,
58 flatStyle.borderBottomLeftRadius || borderRadius,
59 flatStyle.borderBottomLeftRadius || borderRadius,
60 ];
61
62 // support for current react-native-linear-gradient api
63 let startProp = start;
64 let endProp = end;
65 if (start && start.x !== undefined && start.y !== undefined) {
66 startProp = [start.x, start.y];
67 }
68 if (end && end.x !== undefined && end.y !== undefined) {
69 endProp = [end.x, end.y];
70 }
71
72 return (
73 <View {...otherProps} style={style}>
74 <NativeLinearGradient
75 style={{ position: 'absolute', top: 0, left: 0, bottom: 0, right: 0 }}
76 colors={colors.map(processColor)}
77 start={startProp}
78 end={endProp}
79 locations={locations ? locations.slice(0, colors.length) : null}
80 borderRadii={borderRadiiPerCorner}
81 />
82 {children}
83 </View>
84 );
85 }
86}
87
88const NativeLinearGradient = requireNativeComponent(
89 'ExponentLinearGradient',
90 null
91);