ネストされたレイアウト
レイアウトは、ルートのセットに対してネストされたUIとリクエスト処理(ミドルウェア)を提供します
- 共有リクエスト処理:
onRequest
メソッドを追加することで実現します。 - 共有UI: Qwikコンポーネントを
export default
することで実現します。
例
次に、以前に説明したすべての概念を組み合わせて、完全なアプリを構築します。
提案された例では、https://example.com
とhttps://example.com/about
の2つのページを持つサイトが表示されます。目標は、すべてのページに共通のヘッダーとフッターを追加することです。ページ間の唯一の違いは、真ん中のコンテンツです。
┌───────────────────────────────────────────────────┐
│ Header │
├─────────┬─────────────────────────────────────────┤
│ Menu │ <ROUTE_SPECIFIC_CONTENT> │
│ - home │ │
│ - about │ │
│ │ │
├─────────┴─────────────────────────────────────────┤
│ Footer │
└───────────────────────────────────────────────────┘
最初に、3つのコンポーネント<Header>
、<Footer>
、および<Menu>
を作成します。
開発者は、これらのコンポーネントを手動で各ページコンポーネントにコピーアンドペーストできますが、それは反復的でエラーが発生しやすくなります。代わりに、レイアウトを使用して共通部分を自動的に再利用します。
routesディレクトリ
src/
├── components/
│ ├── header.tsx # Header component implementation
│ ├── footer.tsx # Footer component implementation
│ └── menu.tsx # Menu component implementation
└── routes/
├── layout.tsx # Layout implementation using: <Header>, <Footer>, and <Menu>
├── about/
│ └── index.tsx # https://example.com/about
└── index.tsx # https://example.com
src/routes/layout.tsx
src/routes
ディレクトリ以下のすべてのルートで使用されます。Header
、Menu
、およびFooter
コンポーネントをレンダリングし、さらにSlot
コンポーネント下のネストされたルートをレンダリングします。
import { component$, Slot } from '@builder.io/qwik';
export default component$(() => {
return (
<>
<Header />
<Menu />
<Slot /> {/* <== This is where the route will be inserted */}
<Footer />
</>
);
});
src/routes/index.tsx
これはサイトのメインルートです。src/routes/layout.tsx
ファイルのSlot
コンポーネント内でレンダリングされます。Header
、Menu
、またはFooter
コンポーネントは参照されていませんが、それらとともにレンダリングされます。
import { component$ } from '@builder.io/qwik';
export default component$(() => {
return <>Home</>;
});
src/routes/about/index.tsx
src/routes/index.tsx
ファイルと同様に、about
ルートもsrc/routes/layout.tsx
ファイルのSlot
コンポーネント内でレンダリングされます。Header
、Menu
、またはFooter
コンポーネントは参照されていませんが、それらとともにレンダリングされます。
import { component$ } from '@builder.io/qwik';
export default component$(() => {
return <>About</>;
});
アプリを実行すると、QwikはRootLayout
内にネストされたAbout
をレンダリングします。
<RootLayout>
<AboutPage />
</RootLayout>