IntroductionNext.js is a lightweight React server-side rendering application framework. Official website link: www.nextjs.cn/ advantage: Zero configuration automatic compilation and packaging. Optimized for production environments from the start. Hybrid Mode: SSG and SSR Incremental static generation incrementally adds and updates static pre-rendered pages after a build. TypeScript support Fast Refresh A fast, reliable real-time editing experience proven at scale on Facebook-class apps. File system-based routing Each component in the pages directory is a route. API Routes create API endpoints (optional) to provide backend functionality. Built-in support for CSS Code splitting and bundling uses an optimized bundling and splitting algorithm created by the Google Chrome team. Create a Next.js projectManually create a Next.js projectmkdir nextDemo //Create a project npm init //Initialize the project npm i react react-dom next --save //Add dependencies Add shortcut commands in package.json "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "dev" : "next" , "build" : " next build", "start" : "next start" }, Create pages folder and files Create a pages folder in the project root directory and create an index.js file in the pages folder function Index(){ return ( <div>Hello Next.js</div> ) } export default Index Run the project npm run dev creact-next-app quickly creates a projectcreate-next-app can quickly create a Next.js project, it is a scaffolding. npm install -g create-next-app //Global installation of scaffolding create-next-app nextDemo //Create a project based on scaffolding cd nextDemo npm run dev //Run the project Directory structure introduction:
Pages In Next.js, a page is a React component exported from a .js, jsx, .ts or .tsx file, which is stored in the pages directory. Each page uses its file name as a route. If you create a file called pages/about.js and export a React component like the following, you can access it at the /about path. routing There are generally two forms of page jump. The first is to use the tag <Link>, and the second is to jump using js programming, that is, using the Router component. Linkimport React from 'react' import Link from 'next/link' const Home = () => ( <> <div>I am the home page</div> <div><Link href="/pageA" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><a>Go to page A</a></Link></div> <div><Link href="/pageB" rel="external nofollow" ><a>Go to page B</a></Link></div> </> ) export default Home Note: It is very easy to jump using the <Link> tag, but there is another small pitfall that you need to pay attention to, that is, it does not support the situation where brother tags are placed side by side. //Wrong way to write <div> <Link href="/pageA" rel="external nofollow" rel="external nofollow" rel="external nofollow" > <span>Go to page A</span> <span>Front-end blog</span> </Link> </div> //Correct writing <Link href="/pageA" rel="external nofollow" rel="external nofollow" rel="external nofollow" > <a> <span>Go to page A</span> <span>Front-end blog</span> </a> </Link> Routerimport Router from 'next/router' <button onClick={()=>{Router.push('/pageA')}}>Go to page A</button> Parameter passing and receiving In Next.js, parameters can only be passed through query (?id=1), not through (path:id). import Link from 'next/link' //Pass <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>Return to Home Page</a></Link> </> ) } //withRouter is an advanced component of the Next.js framework, used to handle routing export default withRouter(BlogDetail) /****************************************************************************************/ import Router from 'next/router' <button onClick={gotoBlogDetail} >Blog details</button> function gotoBlogDetail(){ Router.push('/blogDetail?bid=23') } //object form function gotoBlogDetail(){ Router.push({ pathname:"/blogDetail", query:{ bid:23 } }) } <Link href={{pathname:'/blogDetail',query:{bid:23}}><a>Blog Details</a></Link> Dynamic Routingpages/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" } Hook Events You can do a lot of things with hook events, such as loading animations during transitions, turning off some resource counters on the page... //When the route changes, Router.events.on('routeChangeStart',(...args)=>{ console.log('1.routeChangeStart->Route starts changing, parameters are:',...args) }) //When the route changes, Router.events.on('routeChangeComplete',(...args)=>{ console.log('routeChangeComplete->Route change completed, parameters:',...args) }) //Browser history before triggering Router.events.on('beforeHistoryChange',(...args)=>{ console.log('3, beforeHistoryChange-> Triggered before changing the browser history, parameters:',...args) }) //When an error occurs in the route jump, Router.events.on('routeChangeError',(...args)=>{ console.log('4, routeChangeError-> Redirect error, parameter:',...args) }) /********************************hash route***********************************/ Router.events.on('hashChangeStart',(...args)=>{ console.log('5, hashChangeStart->hash is executed when the jump starts, the parameters are:',...args) }) Router.events.on('hashChangeComplete',(...args)=>{ console.log('6, hashChangeComplete->hash jump completed, the parameters are:',...args) }) Get data getStaticProps Requesting data at build timeDuring the build phase, the page is built into a static HTML file, so that the HTML file can be directly accessed online with extremely high performance. Use the getStaticProps method to return the data required by the page during the build phase. // 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 Request data on every visitExport an async getServerSideProps method in the page, and next will call this method on the server every time a request is made.
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 Support Adding a global stylesheet To add the stylesheet to your application, import the CSS file in the pages/_app.js file. Adding component-level CSS[name].module.css //login.module.css .loginDiv{ color: red; } //Modify third-party style.loginDiv:global(.active){ color:rgb(30, 144, 255) !important; } import styles from './login.module.css' <div className={styles.loginDiv}/> Next.js allows you to import Sass files with .scss and .sass extensions. You can use components and Sass via CSS Modules and the .module.scss or .module.sass extensions. npm i sass --save If you want to configure the Sass compiler, you can use the sassOptions parameter in the next.config.js file. const path = require('path') module.exports = { sassOptions: { includePaths: [path.join(__dirname, 'styles')], }, } CSS-in-JS Any existing CSS-in-JS solution can be used. The simplest one is inline style: <p style={{ color: 'red' }}>hi there</p> Components using styled-jsx look like this 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 Custom Header <Head> <title>Technical fat people are the fattest! </title> <meta charSet='utf-8' /> </Head> This is the end of this article about the Next.js introductory tutorial. For more Next.js introductory content, please search 123WORDPRESS.COM’s previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: MySQL 5.7.17 winx64 decompression version installation and configuration method graphic tutorial
>>: Using Apache ab to perform http performance testing
1. Mathematical Functions ABS(x) returns the abso...
Table of contents Before MySQL 5.6 After MySQL 5....
1. What is a virtual host? Virtual hosts use spec...
0. Preparation: • Close iTunes • Kill the service...
Typical layout examples As shown in the above pic...
Long story short, today we will talk about using ...
Problem Reproduction When using HTML for editing,...
Install pymysql pip install pymysql 2|0Using pymy...
<br />In one year of blogging, I have person...
1. Abnormal performance of Docker startup: 1. The...
Table of contents 3 ways to deploy projects with ...
Copy code The code is as follows: <span style=...
This is an interview question, which requires the...
Table of contents 1. The concept of process and t...
Be careful when listening for events that are tri...