template.js
模板文件与 layout 类似,它封装布局或页面。与跨路由持续存在并维护状态的布局不同,模板被赋予一个唯一的键,这意味着子客户端组件在导航时重置其状态。
¥A template file is similar to a layout in that it wraps a layout or page. Unlike layouts that persist across routes and maintain state, templates are given a unique key, meaning children Client Components reset their state on navigation.
export default function Template({ children }: { children: React.ReactNode }) {
return <div>{children}</div>
}
export default function Template({ children }) {
return <div>{children}</div>
}
虽然不太常见,但如果你愿意,你可以选择使用模板而不是布局:
¥While less common, you might choose to use a template over a layout if you want:
-
依赖于
useEffect
(例如记录页面浏览量)和useState
(例如每页反馈表)的功能。¥Features that rely on
useEffect
(e.g logging page views) anduseState
(e.g a per-page feedback form). -
更改默认框架行为。例如,布局内的 Suspense Boundaries 仅在第一次加载布局时显示回退,而不是在切换页面时显示回退。对于模板,后备显示在每个导航上。
¥To change the default framework behavior. For example, Suspense Boundaries inside layouts only show the fallback the first time the Layout is loaded and not when switching pages. For templates, the fallback is shown on each navigation.
属性
¥Props
children
(必需的)
¥children
(required)
模板接受 children
属性。例如:
¥Template accepts a children
prop. For example:
<Layout>
{/* Note that the template is automatically given a unique key. */}
<Template key={routeParam}>{children}</Template>
</Layout>
很高兴知道:
¥Good to know:
默认情况下,
template
是 服务器组件,但也可以通过"use client"
指令用作 客户端组件。¥By default,
template
is a Server Component, but can also be used as a Client Component through the"use client"
directive.当用户在共享
template
的路由之间导航时,会安装组件的新实例,重新创建 DOM 元素,客户端组件中不会保留状态,并且会重新同步效果。¥When a user navigates between routes that share a
template
, a new instance of the component is mounted, DOM elements are recreated, state is not preserved in Client Components, and effects are re-synchronized.
版本历史
¥Version History
版本 | 变化 |
---|---|
v13.0.0 | template 推出。 |