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 http://localhost: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 并转到第一篇文章,您将看到以下输出。
