【React Native】安装配置 Expo Router
过去开发React Native
,所使用的路由都是React Navigation。但是这个东西使用起来非常困难,配置无比繁琐。Expo
,为了简化操作,就基于React Navigation
开发了Expo Router
。
Expo Router
用起来就要简单的多了,配置也相对容易很多很多。
不过因为Expo Router
的底层还是React Navigation
,所以也有很多些时候,我们会去React Navigation
官方文档里找一些需要的配置。
使用 create-expo-app
创建一个新的 Expo 应用程序,默认已经安装和配置 Expo Router 。
如果我们手动安装路由,需要先安装依赖:
npx expo install expo-router react-native-safe-area-context react-native-screens expo-linking expo-constants expo-status-bar
然后打开package.json
,将main
这里,修改成:
{"main" : "expo-router/entry"
}
这里是项目的入口配置,要改到expo-router
里面。
之前使用的入口文件是根目录的index.js
,但现在由路由来接管了,所以这些文件现在就没有用了,我们可以直接删除。找到项目根目录的index.js
和App.js
,这两个文件直接删掉。
在根目录里,新建一个app
目录,里面再新建一个index.js
。刚才配置完成后,项目的入口,会自动变成app/index.js
文件。
我们在里面随便放点内容:
import { StyleSheet, Text, View } from 'react-native';export default function App() {return (<View style={styles.container}><Text style={styles.title}>这是一个新的入口!</Text></View>);
}const styles = StyleSheet.create({container: {flex: 1,backgroundColor: '#fff',alignItems: 'center',justifyContent: 'center',},title: {fontSize: 50,width: 200,fontWeight: 'bold',color: '#e29447',}
});
重新启动下项目,运行:
npx expo start
还可以打开根目录的app.json
文件,这里是App
的一些配置。在 expo 属性里面增加上scheme
配置:
{"expo" : {//..."scheme" : "heo-app",}
}
这个配置叫做深度链接
,当这么配置了以后,将来可以通过这种地址:
heo-app://react-native
从别的应用,或者浏览器,可以直接跳转到App
里的对应页面来。
如果你和我现在版本一样:
{"name": "expo-learn","version": "1.0.0","main": "expo-router/entry","scripts": {"start": "expo start","android": "expo start --android","ios": "expo start --ios","web": "expo start --web"},"dependencies": {"expo": "~53.0.17","expo-status-bar": "~2.2.3","react": "19.0.0","react-native": "0.79.5","urlcat": "^3.1.0","expo-router": "~5.1.3","react-native-safe-area-context": "5.4.0","react-native-screens": "~4.11.1","expo-linking": "~7.1.7","expo-constants": "~17.1.7"},"devDependencies": {"@babel/core": "^7.20.0"},"private": true
}
那么按照如上操作会产生一个报错:
ERROR Warning: Invalid prop `style` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.
解决方案如下:
https://stackoverflow.com/questions/79683994/invalid-prop-style-supplied-to-react-fragment-react-fragment-can-only-have
要解决此问题,请转到 node_modules/expo-router/build/views/Navigator.js 并找到 DefaultNavigator() 函数(位于文件末尾附近)。问题就是从那里产生的。
请用以下代码替换该函数:
function DefaultNavigator() {// iOS needs flex: 1 style for proper layoutconst isIOS = process.env.EXPO_OS === 'ios';return (<SlotNavigatorWrapper {...(isIOS ? { style: { flex: 1 } } : {})}><SlotNavigator /></SlotNavigatorWrapper>);
}