模板文件类似于布局,因为它包装着一个布局或页面。与跨路由持久化并保持状态的布局不同,模板被赋予一个唯一的 key,这意味着子级客户端组件在导航时会重置其状态。
当您需要以下情况时,模板会很有用:
useEffect。可以通过从 template.js 文件导出一个默认的 React 组件来定义模板。该组件应接受一个 children prop。

export default function Template({ children }: { children: React.ReactNode }) {
return <div>{children}</div>;
}export default function Template({ children }) {
return <div>{children}</div>;
}在嵌套方面,template.js 会在布局及其子级之间渲染。以下是简化的输出:
<Layout>
{/* Note that the template is given a unique key. */}
<Template key={routeParam}>{children}</Template>
</Layout>children (必需)模板接受一个 children prop。
<Layout>
{/* Note that the template is automatically given a unique key. */}
<Template key={routeParam}>{children}</Template>
</Layout>useEffect 这样的副作用会在组件重新挂载时重新同步。本节将说明模板在导航期间的行为方式。它将逐步展示在每次路由更改时哪些模板会重新挂载以及原因。
使用以下项目树:
app
├── about
│ ├── page.tsx
├── blog
│ ├── [slug]
│ │ └── page.tsx
│ ├── page.tsx
│ └── template.tsx
├── layout.tsx
├── page.tsx
└── template.tsx
从 / 开始,React 树大致如下所示。
注意:示例中显示的
key值仅供说明,你的应用程序中的实际值可能有所不同。
<RootLayout>
{/* app/template.tsx */}
<Template key="/">
<Page />
</Template>
</RootLayout>导航到 /about(第一个段发生更改),根模板的 key 发生更改,它会重新挂载:
<RootLayout>
{/* app/template.tsx */}
<Template key="/about">
<AboutPage />
</Template>
</RootLayout>导航到 /blog(第一个段发生更改),根模板的 key 发生更改,它会重新挂载,并且博客级别的模板会挂载:
<RootLayout>
{/* app/template.tsx (root) */}
<Template key="/blog">
{/* app/blog/template.tsx */}
<Template key="/blog">
<BlogIndexPage />
</Template>
</Template>
</RootLayout>在同一第一个段内导航到 /blog/first-post(子段发生更改),根模板的 key 不变,但博客级别的模板的 key 发生更改,它会重新挂载:
<RootLayout>
{/* app/template.tsx (root) */}
<Template key="/blog">
{/* app/blog/template.tsx */}
{/* remounts because the child segment at this level changed */}
<Template key="/blog/first-post">
<BlogPostPage slug="first-post" />
</Template>
</Template>
</RootLayout>导航到 /blog/second-post(第一个段相同,子段不同),根模板的 key 不变,但博客级别的模板的 key 再次发生更改,它会再次重新挂载:
<RootLayout>
{/* app/template.tsx (root) */}
<Template key="/blog">
{/* app/blog/template.tsx */}
{/* remounts again due to changed child segment */}
<Template key="/blog/second-post">
<BlogPostPage slug="second-post" />
</Template>
</Template>
</RootLayout>| 版本 | 更改 |
|---|---|
v13.0.0 | 引入了 template。 |