五、Styling

郁子大约 1 分钟约 362 字笔记NextJSCodevolution

(一)Global Styles

1.styles/globals.css

html,
body {
  padding: 0;
  margin: 0;
}
a {
  color: inherit;
  text-decoration: none;
}
* {
  box-sizing: border-box;
}
h2 {
  color: orange;
}

2.pages/_app.js

import "../styles/globals.css";

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />;
}

export default MyApp;

3.pages/about.js

function About() {
  return <h2>About Page</h2>;
}

export default About;

4.pages/contact.js

function Contact() {
  return <h2>Contact Page</h2>;
}

export default Contact;

(二)Component Level Styles

1.styles/About.module.css

.highlight {
  color: red;
}

2.styles/Contact.module.css

.highlight {
  color: blue;
}

3.pages/about.js

import styles from "../styles/About.module.css";

function About() {
  return <div className={styles.highlight}>About Page</div>;
}

export default About;

4.pages/contact.js

import styles from "../styles/Contact.module.css";

function Contact() {
  return <div className={styles.highlight}>Contact Page</div>;
}

export default Contact;

(三)Sass Support

yarn add sass

1.styles/_colors.scss

$orange: orange;
$purple: purple;

2.styles/About.module.scss

@import "colors";

.highlightscss {
  color: $orange;
}

3.styles/Contact.module.scss

@import "colors";

.highlightscss {
  color: $purple;
}

4.pages/about.js

import styles from "../styles/About.module.scss";

function About() {
  return <div className={styles.highlightscss}>About Page</div>;
}

export default About;

5.pages/contact.js

import styles from "../styles/Contact.module.scss";

function Contact() {
  return <div className={styles.highlightscss}>Contact Page</div>;
}

export default Contact;

(四)CSS in JS

yarn add styled-components

1.pages/css-in-js.js

import styled from "styled-components";

const Title = styled.h1`
  font-size: 50px;
  color: ${({ theme }) => theme.colors.primary};
`;

function CSSJS() {
  // return <h2 style={{ color: "red" }}>Hello World</h2>;
  return <Title>Styled Component</Title>;
}
export default CSSJS;

2.pages/_app.js

import "../styles/globals.css";
import { ThemeProvider } from "styled-components";

const theme = {
  colors: {
    primary: "#D8152A",
  },
};

function MyApp({ Component, pageProps }) {
  return (
    <ThemeProvider theme={theme}>
      <Component {...pageProps} />
    </ThemeProvider>
  );
}

export default MyApp;

(五)Summary

  • Global:全局样式
    • 在项目中,需要在 pages/_app.js 中导入全局样式文件
  • Component Level:组件样式
    • NextJS 支持使用 [name].module.css 命名的 CSS 模块
  • SASS Support:SASS 样式
    • 需要安装 sass
  • CSS-in-JS Solutions:解决方案
    • 使用内联样式和样式化组件,需要安装 styled-components
上次编辑于: