開始
起步
安裝
npm install --save next react react-dom
Next.js 只支持 React 16
由于某些原因我們不得不放棄支持 React 15
添加下面的配置到package.json 的script字段中
{
"script": {
"dev": "next",
"build": "next build"
"start": "next start"
}
}
之后,文件系統(tǒng)就是主要的API。每一個(gè).js文件都成為一條被自動(dòng)處理和呈現(xiàn)的路徑
在項(xiàng)目中創(chuàng)建 ./pages/index.js
export default () => <div>Welcome to next.js!</div>
運(yùn)行 npm run dev 跳轉(zhuǎn) http://localhost:3000 ,如果想要使用其他端口,你可以使用 npm run dev -- -p <your port here>
目前為止我們做到:
- 代碼的自動(dòng)的轉(zhuǎn)換與打包(使用webpack和babel)
- 代碼熱更新
- 服務(wù)器端渲染
./pages - 靜態(tài)文件服務(wù)
./static/映射到/static/
很簡(jiǎn)單吧!看看這個(gè)案列 sample app - nextgram
代碼的自動(dòng)拆分
您聲明的每個(gè)import都會(huì)捆綁并與每個(gè)頁面一起提供。 這意味著頁面從不加載不必要的代碼
import cowsay from 'cowsay-browser'
export default () =>
<pre>
{cowsay.say({ text: 'hi there!' })}
</pre>
CSS
內(nèi)聯(lián)css支持
案例
我們支持 styled-jsx 書寫CSS, The aim is to support "shadow CSS" similar to Web Components, which unfortunately do not support server-rendering and are JS-only.
export default () =>
<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>
更多案例請(qǐng)查看 styled-jsx 文檔
css-in-js
案列
可以使用現(xiàn)有的 CSS-in-JS 方案,最簡(jiǎn)單的方式是使用內(nèi)聯(lián)
export default () => <p style={{ color:'red' }}>hi</p>
要使用更復(fù)雜的CSS-in-JS解決方案,您通常必須為服務(wù)器端呈現(xiàn)實(shí)現(xiàn)樣式刷新。我們通過允許您定義自己的包裝每個(gè)頁面的自定義<Document>組件來實(shí)現(xiàn)這一點(diǎn)。(To use more sophisticated CSS-in-JS solutions, you typically have to implement style flushing for server-side rendering. We enable this by allowing you to define your own custom <Document> component that wraps each page.)
引入 CSS / Sass / Less / Stylus files
要支持導(dǎo)入.css、.scss、.less或.styl文件,您可以使用這些模塊,它們?yōu)榉?wù)器呈現(xiàn)的應(yīng)用程序配置合理的默認(rèn)值
靜態(tài)文件服務(wù)(比如圖片)
在你的項(xiàng)目根目錄創(chuàng)建一個(gè)static文件,在你的代碼里可以引入這些靜態(tài)文件
export default ()=> <img src="/static/my-image.png" alt='my image' />
head
案列
我們公開了一個(gè)內(nèi)置組件,用于向<head>內(nèi)追加元素, 類似于react-helmet
import Head from 'next/head'
export default () =>
<div>
<Head>
<title>My page title</title>
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
</Head>
<p>Hello world!</p>
</div>
為了避免重復(fù)標(biāo)簽在你的<head>,你可以使用key屬性,這將確保標(biāo)簽只呈現(xiàn)一次:
import Head from 'next/head'
export default () => (
<div>
<Head>
<title>My page title</title>
<meta name="viewport" content="initial-scale=1.0, width=device-width" key="viewport" />
</Head>
<Head>
<meta name="viewport" content="initial-scale=1.2, width=device-width" key="viewport" />
</Head>
<p>Hello world!</p>
</div>
)
上面的案列只有第二個(gè)會(huì)被渲染
在組件被卸載時(shí),
<head>內(nèi)的內(nèi)容也會(huì)卸載,請(qǐng)不要假設(shè)組件更換追加head
請(qǐng)求數(shù)據(jù)與組件的生命周期
案列
當(dāng)您需要狀態(tài)、生命周期鉤子或初始數(shù)據(jù)填充時(shí),您可以導(dǎo)出一個(gè) React.Component(而不是無狀態(tài)函數(shù),如上面所示)
(When you need state, lifecycle hooks or initial data population you can export a React.Component (instead of a stateless function, like shown above):)
import React from 'react'
export default class extends React.Component {
static async getInitialProps({ req }) {
const userAgent = req ? req.headers['user-agent'] : navigator.userAgent
return { userAgent }
}
render() {
return (
<div>
Hello World {this.props.userAgent}
</div>
)
}
}
在頁面加載時(shí)加載數(shù)據(jù),我們使用 getInititialProps, 它是一個(gè)異步的靜態(tài)方法,它可以異步地獲取任何解析為JavaScript普通對(duì)象的內(nèi)容,去填充部分props
從getInitialProps返回的數(shù)據(jù)在服務(wù)器呈現(xiàn)時(shí)被序列化,類似于JSON.stringify。確保getInitialProps返回的對(duì)象是一個(gè)普通對(duì)象,而不使用Date、Map或者set
初始加載的頁面,getInititialProps是僅在服務(wù)器上執(zhí)行的,getInitialProps只有在切換路由或者使用Link和路由api時(shí)才會(huì)在客戶端執(zhí)行
getInitialProps不可以使用在 children components 只可以使用在 Page 中
如果在
getInitialProps中使用一些服務(wù)器模塊,請(qǐng)確保正確地使用它們。否則,它導(dǎo)致你的app變慢
您還可以為無狀態(tài)組件定義getInitialProps生命周期方法:
const Page = ({stars}) =>
<div>
Next stars :{stars}
</div>
Page.getInitialProps = async({req}) => {
const res = await fetch('https://api.github.com/repos/zeit/next.js')
const json = await res.json()
return { stars: json.stargazers_count }
}
export default Page
getInitialProps接收一個(gè) context object 有如下屬性:
- pathname - path section of URL
- query - query string section of URL parsed as an object
- asPath - String of the actual path (including the query) shows in the browser
- req - HTTP request object (server only)
- res - HTTP response object (server only)
- jsonPageRes - Fetch Response object (client only)
- err - Error object if any error is encountered during the rendering
路由
With<Link>
案列
在兩個(gè)頁面之間,客戶端可以使用Link實(shí)現(xiàn)頁面之間的切換
// pages/index.js
import Link from 'next/link'
export default () =>
<div>
Click{' '}
<Link href="/about">
<a>here</a>
</Link>{' '}
to read more
</div>
// pages/about.js
export default () => <p>Welcome to About!</p>
使用
<Link prefetch>可以達(dá)到最大的性能,同時(shí)在后臺(tái)跳轉(zhuǎn)和數(shù)據(jù)預(yù)取 prefetch&Link
客戶端路由的行為與瀏覽器完全相同
- 獲取組件
- 如果定義了
getInitialProps,則獲取數(shù)據(jù)。 如果發(fā)生錯(cuò)誤,則呈現(xiàn)_error.js - 在第1步和第2步完成后,
pushState才會(huì)執(zhí)行,然后組件渲染
每個(gè)頂級(jí)組件都使用以下API接收url屬性:
-
pathname- String of the current path excluding the query string -
query- Object with the parsed query string. Defaults to {} -
asPath- String of the actual path (including the query) shows in the browser -
push(url, as=url)- performs a pushState call with the given url -
replace(url, as=url)- performs a replaceState call with the given url
第二個(gè)作為push和replace的參數(shù)是URL的可選裝飾。 在服務(wù)器上配置自定義路由時(shí)很有用。
With URL Object
案例