Next.js - CSS 支援



在 Next.js 中,我們可以使用內建名為 styled-jsx 的 css-in-js 庫。它允許在 React 元件內編寫 css,並且這些樣式將限制到元件。

在此示例中,我們將建立一個 Container 物件,透過包含其他元件對其進行樣式化。

讓我們更新 元資料 章節中使用的 nextjs 專案。

首先在根級別建立一個 Components 目錄,並如下面新增一個檔案 container.module.css −

.container {
   max-width: 36rem;
   padding: 0 1rem;
   margin: 3rem auto 6rem;
   border: 1px solid red;  
}

在 Components 目錄中建立 container.js 檔案

import styles from './container.module.css'

function Container({ children }) {
   return <div className={styles.container}>{children}</div>
}

export default Container

現在在 first.js 中使用 Container 元件。

import Link from 'next/link'
import Head from 'next/head'
import Container from '../../components/container'

export default function FirstPost() {
   return (
      <>
         <Container>
            <Head>
               <title>My First Post</title>
            </Head>
            <h1>My First Post</h1>
            <h2>
            <Link href="/">
               <a>Home</a>
            </Link>
            </h2>
         </Container>
      </>	  
   )
}

啟動 Next.js 伺服器

執行以下命令啟動伺服器 −.

npm run dev
> nextjs@1.0.0 dev \Node\nextjs
> next

ready - started server on https://:3000
event - compiled successfully
event - build page: /
wait  - compiling...
event - compiled successfully
event - build page: /next/dist/pages/_error
wait  - compiling...
event - compiled successfully

驗證輸出

在瀏覽器中開啟 localhost:3000 並轉到第一個帖子,您將看到以下輸出。

Styled first page
廣告