跳到主要內容

template.js

template 檔案類似於版面配置,它們都會包裝版面配置或頁面。與跨路由持久化並維持狀態的版面配置不同,範本會被賦予唯一的 key,這表示子客戶端元件會在導航時重置其狀態。

app/template.tsx
export default function Template({ children }: { children: React.ReactNode }) {
  return <div>{children}</div>
}
template.js special file

雖然比較少見,但如果您想要以下功能,可能會選擇使用範本而不是版面配置:

  • 依賴 useEffect (例如記錄頁面瀏覽次數) 和 useState (例如每個頁面的意見回饋表單) 的功能。
  • 變更預設框架行為。例如,版面配置內的 Suspense Boundaries 僅在首次載入版面配置時顯示 fallback,而不是在切換頁面時。對於範本,每次導航都會顯示 fallback。

Props

children (必填)

Template 接受 children prop。例如:

輸出
<Layout>
  {/* Note that the template is automatically given a unique key. */}
  <Template key={routeParam}>{children}</Template>
</Layout>

要知道:

  • 預設情況下,template伺服器元件,但也可以透過 "use client" 指令作為客戶端元件使用。
  • 當使用者在共用 template 的路由之間導航時,會掛載元件的新實例、重新建立 DOM 元素、不會在客戶端元件中保留狀態,並且效果會重新同步。

版本歷史

版本變更
v13.0.0引入 template