最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Next.js入門使用教程

 更新時(shí)間:2021年07月14日 16:07:43   作者:purcellhuang  
Next.js 是一個(gè)輕量級(jí)的 React 服務(wù)端渲染應(yīng)用框架。文中通過示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

簡(jiǎn)介

Next.js 是一個(gè)輕量級(jí)的 React 服務(wù)端渲染應(yīng)用框架。

官網(wǎng)鏈接:www.nextjs.cn/

優(yōu)點(diǎn):

零配置
自動(dòng)編譯并打包。從一開始就為生產(chǎn)環(huán)境而優(yōu)化。

混合模式: SSG 和 SSR
在一個(gè)項(xiàng)目中同時(shí)支持構(gòu)建時(shí)預(yù)渲染頁(yè)面(SSG)和請(qǐng)求時(shí)渲染頁(yè)面(SSR)

增量靜態(tài)生成
在構(gòu)建之后以增量的方式添加并更新靜態(tài)預(yù)渲染的頁(yè)面。

支持 TypeScript
自動(dòng)配置并編譯 TypeScript。

快速刷新
快速、可靠的實(shí)時(shí)編輯體驗(yàn),已在 Facebook 級(jí)別的應(yīng)用上規(guī)模上得到驗(yàn)證。

基于文件系統(tǒng)的路由
每個(gè) pages 目錄下的組件都是一條路由。

API 路由
創(chuàng)建 API 端點(diǎn)(可選)以提供后端功能。

內(nèi)置支持CSS
使用 CSS 模塊創(chuàng)建組件級(jí)的樣式。內(nèi)置對(duì) Sass 的支持。

代碼拆分和打包
采用由 Google Chrome 小組創(chuàng)建的、并經(jīng)過優(yōu)化的打包和拆分算法。

創(chuàng)建Next.js項(xiàng)目

手動(dòng)創(chuàng)建Next.js項(xiàng)目

mkdir nextDemo  //創(chuàng)建項(xiàng)目
npm init            //初始化項(xiàng)目
npm i react react-dom next --save           //添加依賴

在package.json中添加快捷鍵命令

 "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev" : "next" ,
    "build" : " next build",
    "start" : "next start"
  },

創(chuàng)建pages文件夾和文件

在項(xiàng)目根目錄創(chuàng)建pages文件夾并在pages文件夾中創(chuàng)建index.js文件

function Index(){
    return (
        <div>Hello Next.js</div>
    )
}
export default Index

運(yùn)行項(xiàng)目

npm run dev

creact-next-app快速創(chuàng)建項(xiàng)目

create-next-app可以快速的創(chuàng)建Next.js項(xiàng)目,它就是一個(gè)腳手架。

npm install -g create-next-app  //全局安裝腳手架
create-next-app nextDemo  //基于腳手架創(chuàng)建項(xiàng)目
cd nextDemo
npm run dev  //運(yùn)行項(xiàng)目

目錄結(jié)構(gòu)介紹:

  • components文件夾: 這里是專門放置自己寫的組件的,這里的組件不包括頁(yè)面,指公用的或者有專門用途的組件。
  • node_modules文件夾:Next項(xiàng)目的所有依賴包都在這里,一般我們不會(huì)修改和編輯這里的內(nèi)容。
  • pages文件夾:這里是放置頁(yè)面的,這里邊的內(nèi)容會(huì)自動(dòng)生成路由,并在服務(wù)器端渲染,渲染好后進(jìn)行數(shù)據(jù)同步。
  • static文件夾: 這個(gè)是靜態(tài)文件夾,比如項(xiàng)目需要的圖片、圖標(biāo)和靜態(tài)資源都可以放到這里。
  • .gitignore文件: 這個(gè)主要是控制git提交和上傳文件的,簡(jiǎn)稱就是忽略提交。
  • package.json文件:定義了項(xiàng)目所需要的文件和項(xiàng)目的配置信息(名稱、版本和許可證),最主要的是使用npm install 就可以下載項(xiàng)目所需要的所有包。

Pages

在 Next.js 中,一個(gè) page(頁(yè)面) 就是一個(gè)從 .js、jsx、.ts 或 .tsx 文件導(dǎo)出(export)的React 組件 ,這些文件存放在 pages 目錄下。每個(gè) page(頁(yè)面)都使用其文件名作為路由(route)。

如果你創(chuàng)建了一個(gè)命名為 pages/about.js 的文件并導(dǎo)出(export)一個(gè)如下所示的 React 組件,則可以通過 /about 路徑進(jìn)行訪問。

路由

頁(yè)面跳轉(zhuǎn)一般有兩種形式,第一種是利用標(biāo)簽<Link>,第二種是用js編程的方式進(jìn)行跳轉(zhuǎn),也就是利用Router組件

Link

import React from 'react'
import Link from 'next/link'
const Home = () => (
  <>
    <div>我是首頁(yè)</div>
    <div><Link href="/pageA" rel="external nofollow"  rel="external nofollow"  rel="external nofollow" ><a>去A頁(yè)面</a></Link></div>
    <div><Link href="/pageB" rel="external nofollow" ><a>去B頁(yè)面</a></Link></div>

  </>
)

export default Home

注意:用<Link>標(biāo)簽進(jìn)行跳轉(zhuǎn)是非常容易的,但是又一個(gè)小坑需要你注意一下,就是他不支持兄弟標(biāo)簽并列的情況。

 //錯(cuò)誤寫法
 <div>
  <Link href="/pageA" rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >
    <span>去A頁(yè)面</span>
    <span>前端博客</span>
  </Link>
</div>

//正確寫法
<Link href="/pageA" rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >
  <a>
    <span>去A頁(yè)面</span>
    <span>前端博客</span>
  </a>
</Link>

Router

import Router from 'next/router'

<button onClick={()=>{Router.push('/pageA')}}>去A頁(yè)面</button>

參數(shù)傳遞與接收

在Next.js中只能通過通過query(?id=1)來傳遞參數(shù),而不能通過(path:id)的形式傳遞參數(shù)。

import Link from 'next/link'

//傳遞
<Link href="/blogDetail?bid=23" rel="external nofollow" ><a>{blog.title}</a></Link>

    
    
//blog.js
import { withRouter} from 'next/router'
import Link from 'next/link'

const BlogDetail = ({router})=>{
    return (
        <>
            <div>blog id: {router.query.name}</div>
            <Link href="/" rel="external nofollow" ><a>返回首頁(yè)</a></Link>
        </>
    )
}
//withRouter是Next.js框架的高級(jí)組件,用來處理路由用的
export default withRouter(BlogDetail)


/************************************************************************************/
import Router from 'next/router'

<button onClick={gotoBlogDetail} >博客詳情</button>

function gotoBlogDetail(){
    Router.push('/blogDetail?bid=23')
}

//object 形式
function gotoBlogDetail(){
    Router.push({
        pathname:"/blogDetail",
        query:{
            bid:23
        }
    })
}

<Link href={{pathname:'/blogDetail',query:{bid:23}}><a>博客詳情</a></Link>

動(dòng)態(tài)路由

pages/post/[pid].js
route : /post/abc  -->  query : { "pid": "abc" }


pages/post/[pid]/[comment].js
route : /post/abc/a-comment  -->  query : { "pid": "abc", "comment": "a-comment" }

鉤子事件

利用鉤子事件是可以作很多事情的,比如轉(zhuǎn)換時(shí)的加載動(dòng)畫,關(guān)掉頁(yè)面的一些資源計(jì)數(shù)器.....

//路由發(fā)生變化時(shí)
Router.events.on('routeChangeStart',(...args)=>{
    console.log('1.routeChangeStart->路由開始變化,參數(shù)為:',...args)
})

//路由結(jié)束變化時(shí)
Router.events.on('routeChangeComplete',(...args)=>{
    console.log('routeChangeComplete->路由結(jié)束變化,參數(shù)為:',...args)
})

//瀏覽器 history觸發(fā)前
Router.events.on('beforeHistoryChange',(...args)=>{
    console.log('3,beforeHistoryChange->在改變?yōu)g覽器 history之前觸發(fā),參數(shù)為:',...args)
})

//路由跳轉(zhuǎn)發(fā)生錯(cuò)誤時(shí)
Router.events.on('routeChangeError',(...args)=>{
    console.log('4,routeChangeError->跳轉(zhuǎn)發(fā)生錯(cuò)誤,參數(shù)為:',...args)
})

/****************************hash路由***********************************/

Router.events.on('hashChangeStart',(...args)=>{
    console.log('5,hashChangeStart->hash跳轉(zhuǎn)開始時(shí)執(zhí)行,參數(shù)為:',...args)
})

Router.events.on('hashChangeComplete',(...args)=>{
    console.log('6,hashChangeComplete->hash跳轉(zhuǎn)完成時(shí),參數(shù)為:',...args)
})

獲取數(shù)據(jù)

getStaticProps

構(gòu)建時(shí)請(qǐng)求數(shù)據(jù)

在build階段將頁(yè)面構(gòu)建成靜態(tài)的html文件,這樣線上直接訪問HTML文件,性能極高。

使用getStaticProps方法在build階段返回頁(yè)面所需的數(shù)據(jù)。
如果是動(dòng)態(tài)路由的頁(yè)面,使用getStaticPaths方法來返回所有的路由參數(shù),以及是否需要回落機(jī)制。

// posts will be populated at build time by getStaticProps()
function Blog({ posts }) {
  return (
    <ul>
      {posts.map((post) => (
        <li>{post.title}</li>
      ))}
    </ul>
  )
}

// This function gets called at build time on server-side.
// It won't be called on client-side, so you can even do
// direct database queries. See the "Technical details" section.
export async function getStaticProps(context) {
  // Call an external API endpoint to get posts.
  // You can use any data fetching library
  const res = await fetch('https://.../posts')
  const posts = await res.json()

  // By returning { props: { posts } }, the Blog component
  // will receive `posts` as a prop at build time
  return {
    props: {
      posts,
    },
  }
}

export default Blog

getServerSideProps

每次訪問時(shí)請(qǐng)求數(shù)據(jù)

頁(yè)面中export一個(gè)async的getServerSideProps方法,next就會(huì)在每次請(qǐng)求時(shí)候在服務(wù)端調(diào)用這個(gè)方法。

  • 方法只會(huì)在服務(wù)端運(yùn)行,每次請(qǐng)求都運(yùn)行一邊getServerSideProps方法
  • 如果頁(yè)面通過瀏覽器端Link組件導(dǎo)航而來,Next會(huì)向服務(wù)端發(fā)一個(gè)請(qǐng)求,然后在服務(wù)端運(yùn)行g(shù)etServerSideProps方法,然后返回JSON到瀏覽器。
function Page({ data }) {
  // Render data...
}

// This gets called on every request
export async function getServerSideProps(context) {
  // Fetch data from external API
  const res = await fetch(`https://.../data`)
  const data = await res.json()

  // Pass data to the page via props
  return { props: { data } }
}

export default Page

CSS支持

添加全局樣式表

要將樣式表添加到您的應(yīng)用程序中,請(qǐng)?jiān)?pages/_app.js 文件中導(dǎo)入(import)CSS 文件。
在生產(chǎn)環(huán)境中,所有 CSS 文件將自動(dòng)合并為一個(gè)經(jīng)過精簡(jiǎn)的 .css 文件。
你應(yīng)該 只在 pages/_app.js 文件中導(dǎo)入(import)樣式表。
從 Next.js 9.5.4 版本開始,你可以在應(yīng)用程序中的任何位置從 node_modules 目錄導(dǎo)入(import) CSS 文件了。
對(duì)于導(dǎo)入第三方組件所需的 CSS,可以在組件中進(jìn)行。

添加組件級(jí)CSS

[name].module.css
//login.module.css
.loginDiv{
    color: red;
}

//修改第三方樣式
.loginDiv :global(.active){
    color:rgb(30, 144, 255) !important;
}
import styles from './login.module.css'
<div className={styles.loginDiv}/>

Next.js 允許你導(dǎo)入(import)具有 .scss 和 .sass 擴(kuò)展名的 Sass 文件。 你可以通過 CSS 模塊以及 .module.scss 或 .module.sass 擴(kuò)展名來使用組件及的 Sass

npm i sass --save

如果要配置 Sass 編譯器,可以使用 next.config.js 文件中的 sassOptions 參數(shù)進(jìn)行配置。

const path = require('path')

module.exports = {
  sassOptions: {
    includePaths: [path.join(__dirname, 'styles')],
  },
}

CSS-in-JS

可以使用任何現(xiàn)有的 CSS-in-JS 解決方案。 最簡(jiǎn)單的一種是內(nèi)聯(lián)樣式:

<p style={{ color: 'red' }}>hi there</p>

使用 styled-jsx 的組件就像這樣

function HelloWorld() {
  return (
    <div>
      Hello world
      <p>scoped!</p>
      <style jsx>{`
        p {
          color: blue;
        }
        div {
          background: red;
        }
        @media (max-width: 600px) {
          div {
            background: blue;
          }
        }
      `}</style>
      <style global jsx>{`
        body {
          background: black;
        }
      `}</style>
    </div>
  )
}

export default HelloWorld

自定義Header

<Head>
    <title>技術(shù)胖是最胖的!</title>
    <meta charSet='utf-8' />
</Head>

到此這篇關(guān)于Next.js入門使用教程的文章就介紹到這了,更多相關(guān)Next.js入門內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

丁青县| 台北市| 西吉县| 岐山县| 曲阳县| 施甸县| 乌拉特前旗| 东乡| 沈丘县| 改则县| 绩溪县| 宝兴县| 龙岩市| 云安县| 巴楚县| 九台市| 白山市| 辉南县| 慈利县| 德惠市| 深州市| 天镇县| 仪征市| 三明市| 双城市| 龙口市| 营山县| 龙岩市| 丰顺县| 济南市| 夏津县| 宿松县| 蛟河市| 黑河市| 阿拉善左旗| 小金县| 金寨县| 马边| 桂平市| 南雄市| 新和县|