|
| 1 | +import React from 'react'; |
| 2 | +import { View, TouchableOpacity, Text } from 'react-native'; |
| 3 | + |
| 4 | +const getAvailableRoutes = navigation => { |
| 5 | + let availableRoutes = []; |
| 6 | + if (!navigation) return availableRoutes; |
| 7 | + |
| 8 | + const parent = navigation.dangerouslyGetParent(); |
| 9 | + if (parent) { |
| 10 | + if (parent.router && parent.router.childRouters) { |
| 11 | + // Grab all the routes the parent defines and add it the list |
| 12 | + availableRoutes = [ |
| 13 | + ...availableRoutes, |
| 14 | + ...Object.keys(parent.router.childRouters), |
| 15 | + ]; |
| 16 | + } |
| 17 | + |
| 18 | + // Recursively work up the tree until there are none left |
| 19 | + availableRoutes = [...availableRoutes, ...getAvailableRoutes(parent)]; |
| 20 | + } |
| 21 | + |
| 22 | + // De-dupe the list and then remove the current route from the list |
| 23 | + return [...new Set(availableRoutes)].filter( |
| 24 | + route => route !== navigation.state.routeName |
| 25 | + ); |
| 26 | +}; |
| 27 | + |
| 28 | +const getRandomColor = () => { |
| 29 | + var letters = '0123456789ABCDEF'; |
| 30 | + var color = '#'; |
| 31 | + for (var i = 0; i < 6; i++) { |
| 32 | + color += letters[Math.floor(Math.random() * 16)]; |
| 33 | + } |
| 34 | + return color; |
| 35 | +}; |
| 36 | + |
| 37 | +const Example = ({ navigation }) => { |
| 38 | + return ( |
| 39 | + <View |
| 40 | + style={{ |
| 41 | + flex: 1, |
| 42 | + alignItems: 'center', |
| 43 | + justifyContent: 'center', |
| 44 | + backgroundColor: getRandomColor(), |
| 45 | + }} |
| 46 | + > |
| 47 | + {getAvailableRoutes(navigation).map(route => ( |
| 48 | + <TouchableOpacity |
| 49 | + onPress={() => navigation.navigate(route)} |
| 50 | + key={route} |
| 51 | + style={{ |
| 52 | + backgroundColor: '#fff', |
| 53 | + padding: 10, |
| 54 | + margin: 10, |
| 55 | + }} |
| 56 | + > |
| 57 | + <Text>{route}</Text> |
| 58 | + </TouchableOpacity> |
| 59 | + ))} |
| 60 | + </View> |
| 61 | + ); |
| 62 | +}; |
| 63 | + |
| 64 | +export default Example; |
0 commit comments