推荐答案
在 Next.js 中,样式编写可以通过以下几种方式实现:
- 全局样式:在
styles目录下创建globals.css文件,并在_app.js中引入。 - 模块化样式:使用 CSS Modules,创建
.module.css文件,并在组件中引入。 - 内联样式:直接在 JSX 元素中使用
style属性。 - CSS-in-JS:使用如
styled-jsx、styled-components或emotion等库。 - Tailwind CSS:通过配置
tailwind.config.js并在globals.css中引入 Tailwind 的样式。
本题详细解读
1. 全局样式
在 styles 目录下创建 globals.css 文件,并在 _app.js 中引入:
/* styles/globals.css */
body {
margin: 0;
padding: 0;
font-family: Arial, sans-serif;
}// pages/_app.js
import '../styles/globals.css';
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}
export default MyApp;2. 模块化样式
使用 CSS Modules,创建 .module.css 文件,并在组件中引入:
/* styles/Button.module.css */
.button {
background-color: blue;
color: white;
padding: 10px 20px;
border: none;
cursor: pointer;
}// components/Button.js
import styles from '../styles/Button.module.css';
export default function Button() {
return <button className={styles.button}>Click Me</button>;
}3. 内联样式
直接在 JSX 元素中使用 style 属性:
// components/Button.js
export default function Button() {
return (
<button style={{ backgroundColor: 'blue', color: 'white', padding: '10px 20px', border: 'none', cursor: 'pointer' }}>
Click Me
</button>
);
}4. CSS-in-JS
使用 styled-jsx、styled-components 或 emotion 等库:
// www.javascriptcn.com code example
// components/Button.js
import styled from 'styled-components';
const Button = styled.button`
background-color: blue;
color: white;
padding: 10px 20px;
border: none;
cursor: pointer;
`;
export default function MyButton() {
return <Button>Click Me</Button>;
}5. Tailwind CSS
通过配置 tailwind.config.js 并在 globals.css 中引入 Tailwind 的样式:
// www.javascriptcn.com code example
// tailwind.config.js
module.exports = {
content: [
'./pages/**/*.{js,ts,jsx,tsx}',
'./components/**/*.{js,ts,jsx,tsx}',
],
theme: {
extend: {},
},
plugins: [],
};/* styles/globals.css */ @tailwind base; @tailwind components; @tailwind utilities;
// components/Button.js
export default function Button() {
return <button className="bg-blue-500 text-white px-4 py-2 rounded">Click Me</button>;
}