教程 > next.js 中文教程 > 阅读:759

next.js 内置对 css 的支持——迹忆客-ag捕鱼王app官网

在 next.js 中,我们可以使用名为 styled-jsx 的内置 css-in-js 库。 它允许在 react 组件中编写 css,并且这些样式将作用于组件。

在此示例中,我们将创建一个 container 对象,该对象将用于通过包含其他组件来设置它们的样式。

让我们更新元数据章节中使用的 nextjs 项目。

首先在根目录创建一个 components 目录,并添加一个文件 container.module.css ,如下

container.module.css

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

在 components 目录下创建 container.js 文件

container.js

import styles from './container.module.css'
function container({ children }) {
   return 
{children}
} export default container

现在在 first.js 中使用 container 组件。

first.js

import link from 'next/link'
import head from 'next/head'
import container from '../../components/container'
export default function firstpost() {
   return (
      <>
         
            
               my first post
            
            
            
         
            
   )
}

启动 next.js 服务器

运行以下命令启动服务器

$ npm run dev
> nextjs@1.0.0 dev /workspace/node/nextjs
> next dev
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
event - compiled client and server successfully in 384 ms (110 modules)

在浏览器中打开 localhost:3000 ,我们将看到以下输出。

next.js 内置对 css 的支持

查看笔记

扫码一下
查看教程更方便
网站地图