1.SPA(单页面应用----存在的问题:首屏加载较慢)
Next.js优点:
1.搭建轻松
2.自带数据同步
3.丰富插件
4.灵活配置
2.配置项目
2.1.手动 自己配置
新建文件夹 ----》 npm init ----》安装依赖 npm i --save react react-dom next ----》
配置命令:
"dev":"next",
"build":"next build",
"start":" next start"
----》新建pages文件夹 新建index.js
import React , {useState} from "react";
function App (){
return (
<h1>
Hello World
</h1>
)
}
export default App;
2.2. create-next-app脚手架
npm i -g create-next-app
npx create-next-app reactNextJsApp
3.pages文件夹下创建的文件直接通过路径即可访问
import React,{useState} from "react";
function App (){
const [name,setName] = useState("ZPWAN");
return (
<div>
<h1>{name}</h1>
<button onClick={()=>{setName("Hello"+name)}}>修改</button>
</div>
)
}
export default App
通过[http://localhost:3000/zpwan](http://localhost:3000/zpwan)
即可访问
更深层次的:[http://localhost:3000/blob/index](http://localhost:3000/blob/index)
4.路由跳转
<Linkhref="/blob/index"><a>link跳转</a></Link>
注意:1.Link标签中不能有多节点
import Router from "next/router";
<button onClick={()=>{Router.push("/zpwan")}}>路由跳转</button>
5.路由传参:
<Link href={"/blob/index?name="+name}>
<a>Link 跳转</a>
</Link>
使用withRouter接收
import Header from "../../components/header";
import {withRouter} from "next/router";
const Blob=({router})=>{
return (
<div>
<Header></Header>
<h1>
{router.query.name}
</h1>
{/* <button onClick={()=>{Router.push("/zpwan")}}>路由跳转</button> */}
</div>
)
}
export default withRouter(Blob)
Router.push({
pathname:"/blob/index",
query:{name:"cessss"}
})
路由钩子:
routerChangeStart
routerChangeComplete
beforeHistoryChange
routeChangeError
hashChangeStart
hashChangeComplete
添加样式:
1.
import Header from "../../components/header";
import Router, { withRouter } from "next/router";
const Blob = ({ router, list }) => {
return (
<div>
<Header></Header>
<h1 className="hhhh">
{router.query.name}
</h1>
<button onClick={() => { Router.push("/zpwan") }}>路由跳转</button>
<style jsx>
{`
.hhhh{
color:red
}
`}
</style>
</div>
)
}
export default withRouter(Blob)
2. npm - --save @zeit/next-css
然后添加下面的配置文件即可成功引入相关css文件了
新建next.config.js配置文件
image.png
设置页面标题
import Head from "next/head";
<Head>
<title>这是测试标题</title>
</Head>
网友评论