Next.js是一个用于在服务端渲染React应用程序的框架,它提供了一种简单的方法来创建高性能的Web应用程序。以下是一些Next.js的开发指南和示例代码。
- 创建一个新的Next.js项目:
 
npx create-next-app my-app- 在Next.js中导入图片:
 
import Image from 'next/image'
 
function Home() {
  return (
    <div>
      <Image src="/profile.jpg" alt="Profile Picture" width={500} height={500} />
    </div>
  )
}
 
export default Home- 使用Next.js的动态路由:
 
在pages目录下创建一个[postId].js文件,Next.js将自动生成基于postId的动态路由。
function Post({ post }) {
  return <h1>{post.title}</h1>
}
 
export async function getStaticPaths() {
  // Call an external API endpoint to get posts
  const res = await fetch('https://.../posts')
  const posts = await res.json()
 
  // Get the paths
  const paths = posts.map(post => ({
    params: { postId: post.id },
  }))
 
  // The paths that will be pre-rendered
  return { paths, fallback: false }
}
 
export async function getStaticProps({ params }) {
  // Call an external API endpoint with the postId
  const res = await fetch(`https://.../posts/${params.postId}`)
  const post = await res.json()
 
  // Pass post data to the page via props
  return { props: { post } }
}
 
export default Post- 使用Next.js的
getServerSideProps方法获取服务器端数据: 
export async function getServerSideProps(context) {
  const { data } = await axios.get(`https://.../data/${context.query.id}`)
  return { props: { data } }
}
 
function DataPage({ data }) {
  return <div>{data}</div>
}
 
export default DataPage- 使用Next.js的
Link组件进行导航: 
import Link from 'next/link'
 
function Home() {
  return (
    <div>
      <Link href="/about">
        <a>About Page</a>
      </Link>
    </div>
  )
}
 
export default Home- 配置Next.js的自定义页面路由:
 
在pages目录下创建一个_app.js文件,可以用来全局配置应用程序的外观。
import '../styles/globals.css'
 
function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}
 
export default MyApp这些是Next.js的一些基本特性和用法,实际开发中可能还会涉及到更复杂的配置和API。