# nextjs基础

# 路由

# 无需配置的路由

pages/posts/first-post.js 文件相当于是以下路由 /posts/first-post route.

# 代码分割和预加载

  • js自动进行代码分割,因此每个页面只加载该页面所需的内容。这意味着在呈现主页时,最初不会提供其他页面的代码。
  • 在Next.js的产品构建中,每当Link组件出现在浏览器的viewport中,Next.js会自动在后台预取链接页面的代码。当您单击该链接时,目标页面的代码已经在后台加载,页面转换将几乎立即完成!

# Link标签

Link 标签代替 a 标签

import Link from 'next/link'
...
<h1 className="title">
  Read{' '}
  <Link href="/posts/first-post">
    <a>this page!</a>
  </Link>
</h1>

# 静态资源、metadata、css

# Image标签

import Image from 'next/image'

const YourComponent = () => (
  <Image
    src="/images/profile.jpg" // Route of the image file
    height={144} // Desired size with correct aspect ratio
    width={144} // Desired size with correct aspect ratio
    alt="Your Name"
  />
)

# Head标签

会向head中,注入内容

import Head from 'next/head'
<Head>
    <title>First Post</title>
</Head>

# 加载Script

next/script 是HTML <script> 元素的扩展,并在获取和执行额外脚本时进行优化。

import Script from 'next/script'
export default function FirstPost() {
  return (
    <>
      <Head>
        <title>First Post</title>
      </Head>
      <Script
        src="https://connect.facebook.net/en_US/sdk.js"
        strategy="lazyOnload"
        onLoad={() =>
          console.log(`script loaded correctly, window.FB has been populated`)
        }
      />
      <h1>First Post</h1>
      <h2>
        <Link href="/">
          <a>Back to home</a>
        </Link>
      </h2>
    </>
  )
}

# CSS Styling

直接import

import '../styles.css'

// This default export is required in a new `pages/_app.js` file.
export default function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

CSS Modules

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

export function Button() {
  return (
    <button
      type="button"
      // Note how the "error" class is accessed as a property on the imported
      // `styles` object.
      className={styles.error}
    >
      Destroy
    </button>
  )
}

CSS-in-JS

<style jsx global>{`
html,
body {
    padding: 0;
    margin: 0;
    font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto,
    Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue,
    sans-serif;
}

* {
    box-sizing: border-box;
}
`}
</style>

# Global Styles

加载全局css,创建 pages/_app.jsstyles/global.css

import '../styles/global.css'

export default function App({ Component, pageProps }) {
  return <Component {...pageProps} />
}
html,
body {
  padding: 0;
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, Ubuntu,
    Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
  line-height: 1.6;
  font-size: 18px;
}

* {
  box-sizing: border-box;
}

a {
  color: #0070f3;
  text-decoration: none;
}

a:hover {
  text-decoration: underline;
}

img {
  max-width: 100%;
  display: block;
}

# Layouts

# 创建一个layout

components 下创建 layout.js

export default function Layout({ children }) {
  return <div>{children}</div>
}
lastUpdate: 4/18/2022, 1:08:54 AM