template.js

模板 (template) 文件与 布局 (layout) 类似,都会包裹每个子布局或页面。但与跨路由保持状态的布局不同,模板会在导航时为每个子元素创建新的实例。

export default function Template({ children }: { children: React.ReactNode }) {
  return <div>{children}</div>
}
template.js 特殊文件

在以下情况下,您可能会选择使用模板而非布局(虽然这种情况较少见):

  • 需要使用依赖 useEffect 的功能(如记录页面访问)或 useState(如每页的反馈表单)
  • 需要更改框架的默认行为。例如,布局内的 Suspense Boundaries 仅在首次加载布局时显示回退状态,而模板会在每次导航时都显示回退状态

属性

children (必需)

模板组件应接收并使用 children 属性。template 会在 布局 (layout) 与其子元素之间渲染。例如:

Output
<Layout>
  {/* 注意模板会获得唯一的 key */}
  <Template key={routeParam}>{children}</Template>
</Layout>

须知:

版本历史

版本变更内容
v13.0.0引入 template 功能

On this page