了解 Expo Router 使用的基于文件的路由约定。
当在 app 目录下创建一个文件时,它会自动成为 app 中的一个路由。例如,以下文件将创建以下路由:
¥When a file is created in the app directory, it automatically becomes a route in the app. For example, the following files will create the following routes:
app
index.js
matches '/'
home.js
matches '/home'
[user].js
matches dynamic paths like '/expo' or '/evanbacon'
settings
index.js
matches '/settings'
¥Pages
页面是通过从应用目录中的文件导出 React 组件作为默认值来定义的。从中导出的文件必须使用 .js
、.jsx
、.tsx
、.ts
扩展名之一。
¥Pages are defined by exporting a React component as the default value from a file in the app directory. The file they are exported from must use one of the .js
, .jsx
, .tsx
, .ts
extensions.
例如,在项目中创建 app 目录,然后在其中创建一个文件 index.js。然后,添加以下代码片段:
¥For example, create the app directory in your project and then create a file index.js inside it. Then, add the following snippet:
使用 React Native 的 <Text>
组件在任何平台上渲染文本。
¥Render text on any platform with the <Text>
component from React Native.
import { Text } from 'react-native';
export default function Page() {
return <Text>Home page</Text>;
}
或者,你可以编写仅限 Web 的 React 组件,例如 <div>
、<p>
等。但是,这些不会在原生平台上渲染。
¥Alternatively, you can write web-only React components such as <div>
, <p>
, and so on. However, these won't render on native platforms.
export default function Page() {
return <p>Home page</p>;
}
上面的例子匹配了应用和浏览器中的 /
路由。名为 index 的文件与父目录匹配,并且不添加路径段。例如,app/settings/index.js 与应用中的 /settings
匹配。
¥The above example matches the /
route in the app and the browser. Files named index match the parent directory and do not add a path segment. For example, app/settings/index.js matches /settings
in the app.
应用目录不支持平台扩展(例如 .ios.js、.native.ts)。有关详细信息,请参阅 特定于平台的模块。
¥Platform extensions (for example, .ios.js, .native.ts) are not supported in the app directory. See Platform-specific modules, for more information.
¥Dynamic routes
动态路由与给定网段级别的任何不匹配路径相匹配。
¥Dynamic routes match any unmatched path at a given segment level.
路由 | 匹配的网址 |
---|---|
应用/博客/[slug].js | /blog/123 |
应用/博客/[...rest].js | /blog/123/settings |
优先级高的路由会先于动态路由进行匹配。例如,/blog/bacon
将在 blog/[id].js 之前匹配 blog/bacon.js。
¥Routes with higher specificity will be matched before a dynamic route. For example, /blog/bacon
will match blog/bacon.js before blog/[id].js.
可以使用剩余语法 (...
) 在单个路由中匹配多个 slugs。例如,app/blog/[...id].js 匹配 /blog/123/settings
。
¥Multiple slugs can be matched in a single route by using the rest syntax (...
). For example, app/blog/[...id].js matches /blog/123/settings
.
动态段可在页面组件中作为 搜索参数 进行访问。
¥Dynamic segments are accessible as search parameters in the page component.
import { useLocalSearchParams } from 'expo-router';
import { Text } from 'react-native';
export default function Page() {
const { slug } = useLocalSearchParams();
return <Text>Blog post: {slug}</Text>;
}