UNPKG

2.73 kBJavaScriptView Raw
1/* eslint-disable react/no-unused-prop-types */
2import isEqual from 'lodash/isEqual';
3import pick from 'lodash/pick';
4import React, { PureComponent } from 'react';
5import PropTypes from 'prop-types';
6import { TabBarIOS } from './react-native';
7
8const ICON_PROP_NAMES = ['iconName', 'iconSize', 'iconColor'];
9const SELECTED_ICON_PROP_NAMES = [
10 ...ICON_PROP_NAMES,
11 'selectedIconName',
12 'selectedIconColor',
13];
14
15const arePropsEqual = keys => (prevProps, nextProps) =>
16 isEqual(pick(prevProps, keys), pick(nextProps, keys));
17
18const areIconPropsEqual = arePropsEqual(ICON_PROP_NAMES);
19const areSelectedIconPropsEqual = arePropsEqual(SELECTED_ICON_PROP_NAMES);
20
21export default function createTabBarItemIOSComponent(
22 IconNamePropType,
23 getImageSource
24) {
25 return class TabBarItemIOS extends PureComponent {
26 static propTypes = {
27 iconName: IconNamePropType.isRequired,
28 selectedIconName: IconNamePropType,
29 iconSize: PropTypes.number,
30 iconColor: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
31 selectedIconColor: PropTypes.oneOfType([
32 PropTypes.string,
33 PropTypes.number,
34 ]),
35 };
36
37 static defaultProps = {
38 iconSize: 30,
39 };
40
41 state = {
42 icon: undefined,
43 selectedIcon: undefined,
44 };
45
46 componentDidMount() {
47 this.updateIconSource();
48 this.updateSelectedIconSource();
49 }
50
51 componentDidUpdate(prevProps) {
52 if (!areIconPropsEqual(prevProps, this.props)) {
53 this.updateIconSource();
54 }
55 if (!areSelectedIconPropsEqual(prevProps, this.props)) {
56 this.updateSelectedIconSource();
57 }
58 }
59
60 async updateIconSource() {
61 const { iconName, iconSize, iconColor } = this.props;
62 if (iconName) {
63 const icon = await getImageSource(iconName, iconSize, iconColor);
64 this.setState({ icon });
65 // eslint-disable-next-line react/destructuring-assignment
66 } else if (this.state.icon) {
67 this.setState({ icon: undefined });
68 }
69 }
70
71 async updateSelectedIconSource() {
72 const {
73 iconName,
74 iconColor,
75 iconSize,
76 selectedIconName,
77 selectedIconColor,
78 } = this.props;
79 if (selectedIconName || selectedIconColor) {
80 const selectedIcon = await getImageSource(
81 selectedIconName || iconName,
82 iconSize,
83 selectedIconColor || iconColor
84 );
85 this.setState({ selectedIcon });
86 // eslint-disable-next-line react/destructuring-assignment
87 } else if (this.state.selectedIcon) {
88 this.setState({ selectedIcon: undefined });
89 }
90 }
91
92 render() {
93 return <TabBarIOS.Item {...this.state} {...this.props} />;
94 }
95 };
96}
97
\No newline at end of file