動態(tài)表單
初始化必須給{}賦值表單的name與值姆钉,否則會報不受控(即使是遍歷出來的表單)
動態(tài)樣式
方案一:CSS Module + classnames
import classNames from 'classnames'
function Render () {
return (
<div className={
classNames(
ProgressStyles.fragment, {
[ProgressStyles.fragmentActive]: idx <= activeIndex
}
)
} key={idx}>{idx}</div>
)
}
Notes: CSS Modules不支持連字符涮雷、下劃線銜接钧萍。
.fragment {
background: rgba(0, 0, 0, 0.06);
flex: 1;
& + & {
margin: {
left: 10px;
};
}
&Active {
background: #0F68FF;
}
}
方案二:樣式滲透
:global
:global {
.ant-select-selector {
border: 1px solid #E5E5E5;
background: linear-gradient(125.85deg, rgba(59, 63, 238, 0.1) 0%, rgba(57, 159, 254, 0.1) 100%);
@media screen and (min-width: 550px) {
height: nth($lineHeight, 1)!important;
line-height: nth($lineHeight, 1)!important;
}
@media screen and (max-width: 550px) {
height: nth($lineHeight, 2)!important;
line-height: nth($lineHeight, 2)!important;
}
}
.ant-select-selection-placeholder {
@include placeholder;
}
}
:global(.swiper-slide) {
cursor: pointer;
}
組件定義
Slot定義
SwiperCommon組件的調(diào)用,需要用SwiperCommon內(nèi)部遍歷的列表項數(shù)據(jù):
export default function Render () {
return (
<SwiperCommon className="newsSwiper" metas={data.list} options={}>
{
(meta) => (
<section className={NewsStyles.swiperSlide} onClick={() => handleClick(meta.id)}>
<div className={NewsStyles.coverWrapper}>
<Image alt={meta.title} src={meta.cover} className={NewsStyles.img}/>
</div>
<p className={NewsStyles.slideTitle}>{meta.title}</p>
<p className={NewsStyles.summary}>{meta.summary}</p>
<p className={NewsStyles.date}>{meta.time}</p>
</section>
)
}
</SwiperCommon>
)
}
ScopedSlot定義:
import { useEffect } from 'react';
import SwiperCommonStyles from '@/styles/swiper-common.module.scss'
function SwiperCommon ({ children, metas = [], className: externalClass, options = {}}) {
useEffect(() => {
const swiper = new Swiper(`.${externalClass || 'swiper'}`, {
direction: 'horizontal',
centerInsufficientSlides: true,
...options
});
}, [externalClass, options])
return (
<>
{
metas.length && (
<div className={classNames(SwiperCommonStyles.swiper, `swiper ${externalClass}`)}>
<div className={classNames(SwiperCommonStyles.swiperWrapper, 'swiper-wrapper')}>
{
metas.map((item, idx) => (
<div key={idx} className={classNames(SwiperCommonStyles.swiperSlide, 'swiper-slide')}>
{children && children(item)}
</div>
))
}
</div>
</div>
)
}
</>
)
}
export default SwiperCommon
參數(shù)解構(gòu)
<!--閉合標簽使用時晓避,組件參數(shù)類型聲明中包含children-->
<NavigationBar
title="This is title"
>
</NavigationBar>
<!--空標簽使用時疫赎,組件參數(shù)類型聲明中不包含children-->
<NavigationBar
title="This is title"
/>
組件的參數(shù)解構(gòu):
import NavigationBarStyles from "../styles/navigationbar.module.scss"
function Navigationbar ({ children, title = "", historyBack = false }) {
return (
<div className={NavigationBarStyles.container}>
{historyBack && (<div className={NavigationBarStyles.historyBack}><</div>)}
<NavigationbarContent title={title}>{children}</NavigationbarContent>
</div>
)
}
export default Navigationbar
Notes:
-
<NavigationBar />
形式調(diào)用組件禽炬,解構(gòu)出來的children
為undefined
-
<NavigationBar></NavigationBar>
形式調(diào)用組件,即使子節(jié)點為空蟹瘾,也能解構(gòu)出來的children
為[]
全局SCSS變量配置
https://stackoverflow.com/questions/60951575/next-js-using-sass-variables-from-global-scss
const path = require('path');
const nextConfig = (phase, { defaultConfig }) => {
if ('sassOptions' in defaultConfig) {
defaultConfig['sassOptions'] = {
includePaths: [path.join(__dirname, 'styles')],
prependData: `@import "utils.scss";`,
};
}
return defaultConfig;
};
module.exports = nextConfig;
全局可訪問變量
在根目錄下定義.env
圾浅、.env.development
、.env.production
憾朴、.env.local
文件
Node環(huán)境
HOSTNAME=localhost
PORT=8080
HOST=http://$HOSTNAME:$PORT
Notes:
- 以上變量在Node環(huán)境中可通過
process.env.HOSTNAME
形式獲取狸捕,無法在瀏覽器中獲取伊脓; - 可以通過
$Variable
的形式府寒,在另一個變量定義中引用其他變量
Browser環(huán)境
NEXT_PUBLIC_API_BASEURL=http://127.0.0.1:3000
Notes:
- 以上變量可以在Node魁衙、Browser環(huán)境中可通過
process.env.NEXT_PUBLIC_API_BASEURL
形式獲取 - 以
NEXT_PUBLIC_
前綴定義變量可以暴露在瀏覽器環(huán)境;
限制
- 只能通過
process.env.VarName
的形式訪問株搔,無法通過解構(gòu)剖淀、[變量]形式訪問-
process.env[varName]
——> Error -
const env = process.env
——> Error
-
類型聲明
https://dmitripavlutin.com/typescript-react-components/
https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/index.d.ts
圖片渲染
- 使用
'next/image'
提供的組件,會提供圖片優(yōu)化 — 懶加載 - 使用
'next/image'
提供的組件纤房,必須設(shè)定圖片尺寸纵隔,圖片尺寸若要根據(jù)父級尺寸,需設(shè)置父元素position: relative
炮姨,<Image layout="fill"...
— 此時生成的img
標簽是絕對定位的捌刮。
import Image from 'next/image';
import welcomeStyles from '../styles/welcome.module.scss';
export default function Home() {
return (
<>
<section className={welcomeStyles.navigationbar}>
<h1 className='navigationbar-title'>new world</h1>
</section>
<section className={welcomeStyles.main}>
<h2 className={welcomeStyles.title}>Welcome new world!</h2>
<div className={welcomeStyles.cover}>
<Image layout="fill" objectFit="cover" src="/images/entries/wel.png" alt="" />
</div>
</section>
</>
);
}
客戶端渲染
useEffect(() => {
import("../lib/flexible");
import("../lib/flexibleHelper");
}, []);
api Route
api定義
范指/pages/api/**/*.js
路徑下的文件舒岸,該處主要是轉(zhuǎn)接服務(wù)端接口绅作,中轉(zhuǎn)前端數(shù)據(jù)結(jié)構(gòu)。
// /pages/api/blog
export default function handler(req, res) { // 導(dǎo)出的函數(shù)方法名無實際意義
res.status(200).json({ name: 'John Doe' })
}
Notes: 該JavaScript是服務(wù)端代碼蛾派,而非H5前端代碼俄认;
api訪問
export async function getStaticProps(context) {
const res = await fetch(`${process.env.BaseUrl}/api/blog`)
const features = await res.json()
return {
props: {
features,
},
}
}
export default function Blog ({features}) {
const features = response
return (
<>
<News meta={features.NewsResponse} />
</>
)
}
Notes:
- 前端必須通過http(s)協(xié)議請求,所以洪乍,必須啟動服務(wù)才可以訪問Api Route
-
getStaticProps
只能在Pages
下調(diào)用眯杏,在componets
中調(diào)用無效
導(dǎo)出純靜態(tài)頁面
導(dǎo)出不需要服務(wù)配置,可獨立訪問的HTML靜態(tài)頁面(注意:SSG也是需要服務(wù)端配置的)
- 示例中的Nextjs在13.3(不含)以下版本:
13.2.4
- 頁面內(nèi)的數(shù)據(jù)都是本地Mock的JSON數(shù)據(jù)
- 修改
next.config.js
配置:
const nextConfig = (phase, {defaultConfig}) => {
defaultConfig.reactStrictMode = true
defaultConfig.exportPathMap = async function (defaultPathMap) {
return {
'/': { page: '/' },
'/news': { page: '/news' },
'/blog': { page: '/blog' },
}
}
defaultConfig.images.unoptimized = true
return defaultConfig
}
module.exports = nextConfig
- 配置
exportPathMap
字段壳澳,官網(wǎng)文檔聲明13.3版本以上會自動生成岂贩,無需配置 - 配置
images.unoptimized = true
,不允許優(yōu)化圖片巷波,否則會報錯
- 補充
package#scripts
萎津,運行npm run export
"scripts": {
"dev": "next dev",
"build": "next build",
"export": "next build && next export && npm run build-static-repair-index && npm run build-favicon-repair-index && npm run build-logo-repair-index",
"build-static-repair-index": "replace-in-files --string \"/_next/static\" --replacement \"/_next/static\" out/index.html",
"build-favicon-repair-index": "replace-in-files --string \"/favicon.ico\" --replacement \"./favicon.ico\" out/*.html",
"build-logo-repair-index": "replace-in-files --string \"/logo*.png\" --replacement \"./logo*.png\" out/*.html",
"start": "next start",
"lint": "next lint"
},
- 靜態(tài)打包后的資源引用地址不對,目前沒找到配置項可用褥紫,需借助于
replace-in-files
單獨處理資源引用姜性。
- 將
/out
中的靜態(tài)資源部署即可