在日常開(kāi)發(fā)中,團(tuán)隊(duì)中每個(gè)人組織代碼的方式不盡相同。下面我們就從代碼結(jié)構(gòu)的角度來(lái)看看如何組織一個(gè)更加優(yōu)雅的 React 組件!
我們通常會(huì)在組件文件頂部導(dǎo)入組件所需的依賴項(xiàng)。對(duì)于不同類別的依賴項(xiàng),建議對(duì)它們進(jìn)行分組,這有助于幫助我們更好的理解組件。可以將導(dǎo)入的依賴分為四類:
// 外部依賴import React from "react";import { useRouter } from "next/router";// 內(nèi)部依賴import { Button } from "../src/components/button";// 本地依賴import { Tag } from "./tag";import { Subscribe } from "./subscribe";// 樣式import styles from "./article.module.scss";
對(duì)導(dǎo)入依賴項(xiàng)進(jìn)行手動(dòng)分組可能比較麻煩,Prettier 可以幫助我們自動(dòng)格式化代碼。可以使用 prettier-plugin-sort-imports 插件來(lái)自動(dòng)格式化依賴項(xiàng)導(dǎo)入。需要在項(xiàng)目根目錄創(chuàng)建prettier.config.js配置文件,并在里面配置規(guī)則:
module.exports = { // 其他 Prettier 配置 importOrder: [ // 默認(rèn)情況下,首先會(huì)放置外部依賴項(xiàng) // 內(nèi)部依賴 "^../(.*)", // 本地依賴項(xiàng),樣式除外 "^./((?!scss).)*$", // 其他 "^./(.*)", ], importOrderSeparation: true,};
下面是該插件官方給出的例子,輸入如下:
import React, { FC, useEffect, useRef, ChangeEvent, KeyboardEvent,} from 'react';import { logger } from '@core/logger';import { reduce, debounce } from 'lodash';import { Message } from '../Message';import { createServer } from '@server/node';import { Alert } from '@ui/Alert';import { repeat, filter, add } from '../utils';import { initializeApp } from '@core/app';import { Popup } from '@ui/Popup';import { createConnection } from '@server/database';
格式化之后的輸出如下:
import { debounce, reduce } from 'lodash';import React, { ChangeEvent, FC, KeyboardEvent, useEffect, useRef,} from 'react';import { createConnection } from '@server/database';import { createServer } from '@server/node';import { initializeApp } from '@core/app';import { logger } from '@core/logger';import { Alert } from '@ui/Alert';import { Popup } from '@ui/Popup';import { Message } from '../Message';import { add, filter, repeat } from '../utils';
prettier-plugin-sort-imports:https://github.com/trivago/prettier-plugin-sort-imports
在導(dǎo)入依賴項(xiàng)的下方,通常會(huì)放那些使用 TypeScript 或 Flow 等靜態(tài)類型檢查器定義的文件級(jí)常量和類型定義。
組件中的所有 magic 值,例如字符串或者數(shù)字,都應(yīng)該放在文件的頂部,導(dǎo)入依賴項(xiàng)的下方。由于這些都是靜態(tài)常量,這意味著它們的值不會(huì)改變。因此將它們放在組件中是沒(méi)有意義的,因?yàn)榉旁诮M件中的話,它們會(huì)在每次重新渲染組件時(shí)重新創(chuàng)建。
const MAX_READING_TIME = 10;const META_TITLE = "Hello World";
對(duì)于更復(fù)雜的靜態(tài)數(shù)據(jù)結(jié)構(gòu),可以將其提取到一個(gè)單獨(dú)的文件中,以保持組件代碼整潔。
下面是使用 TypeScript 聲明的組件 props 的類型:
interface Props { id: number; name: string; title: string; meta: Metadata;}
如果這個(gè) props 的類型不需要導(dǎo)出,可以使用 Props 作為接口名稱,這樣可以幫助我們立即識(shí)別組件 props 的類型定義,并將其與其他類型區(qū)分開(kāi)。
只有當(dāng)這個(gè) Props 類型需要在多個(gè)組件中使用時(shí),才需要添加組件名稱,例如ButtonProps,因?yàn)樗趯?dǎo)入另一個(gè)組件時(shí),不應(yīng)該與另一個(gè)組件的Props類型沖突。
定義函數(shù)組件的方式有兩種:函數(shù)聲明和箭頭函數(shù), 推薦使用函數(shù)聲明的形式,因?yàn)檫@就是語(yǔ)法聲明的內(nèi)容:函數(shù)。官方文檔的示例中也使用了這種方法:
function Article(props: Props) { /**/}
只會(huì)在必須使用 forwardRef 時(shí)才使用箭頭函數(shù):
const Article = React.forwardRef<HTMLArticleElement, Props>( (props, ref) => { /**/ });
通常會(huì)在組件最后默認(rèn)導(dǎo)出組件:
export default Article;
接下來(lái),我們就需要在組件里面進(jìn)行變量的聲明。注意,即使使用 const 聲明,這里也稱為變量,因?yàn)樗鼈兊闹低ǔ?huì)在不同的渲染之間發(fā)生變化,只有在執(zhí)行單個(gè)渲染過(guò)程時(shí)是恒定的。
const { id, name, title } = props;const router = useRouter();const initials = getInitials(name);
這里通常包含在組件級(jí)別使用的所有變量,使用 const 或 let 定義,具體取決于它們?cè)阡秩酒陂g是否更改其值:
一些較大的組件可能需要在組件中聲明很多變量。這種情況下,建議根據(jù)它們的初始化方法或者用途對(duì)它們進(jìn)行分組:
// 框架 hooksconst router = useRouter();// 自定義 hooksconst user = useLoggedUser();const theme = useTheme();// 從 props 中解構(gòu)的數(shù)據(jù)const { id, title, meta, content, onSubscribe, tags } = props;const { image, author, date } = meta;// 組件狀態(tài)const [email, setEmail] = React.useState("");const [showMenu, toggleMenu] = React.useState(false);const [activeTag, dispatch] = React.useReducer(reducer, tags);// 記憶數(shù)據(jù)const subscribe = React.useCallback(onSubscribe, [id]);const summary = React.useMemo(() => getSummary(content), [content]);// refsconst sideMenuRef = useRef<HTMLDivElement>(null);const subscribeRef = useRef<HTMLButtonElement>(null);// 計(jì)算數(shù)據(jù)const initials = getInitials(author);const formattedDate = getDate(date);
變量分組的方法在不同組件之間可能會(huì)存在很大的差異,它取決于變量的數(shù)量和類型。關(guān)鍵是要將相關(guān)變量放在一起,在不同組之間添加一個(gè)空行來(lái)提高代碼的可讀性。
注:上面代碼中的注釋僅用于標(biāo)注分組類型,在實(shí)際項(xiàng)目中不會(huì)寫這些注釋。
Effects 部分通常會(huì)寫在變量聲明之后,它們可能是React中最復(fù)雜的構(gòu)造,但從語(yǔ)法的角度來(lái)看它們非常簡(jiǎn)單:
useEffect(() => { setLogo(theme === "dark" ? "white" : "black");}, [theme]);
任何包含在effect之內(nèi)但是在其外部定義的變量,都應(yīng)該包含在依賴項(xiàng)的數(shù)組中。
除此之外,還應(yīng)該使用return來(lái)清理副作用:
useEffect(() => { function onScroll() { /*...*/ } window.addEventListener("scroll", onScroll); return () => window.removeEventListener("scroll", onScroll);}, []);
組件的核心就是它的內(nèi)容,React 組件的內(nèi)容使用 JSX 語(yǔ)法定義并在瀏覽器中呈現(xiàn)為 HTML。所以,推薦將函數(shù)組件的 return 語(yǔ)句盡可能靠近文件的頂部。其他一切都只是細(xì)節(jié),它們應(yīng)該放在文件較下的位置。
function Article(props: Props) { // 變量聲明 // effects // ? 自定義的函數(shù)不建議放在 return 部分的前面 function getInitials() { /*...*/ } return /* content */;}export default Article;
function Article(props: Props) { // 變量聲明 // effects return /* content */; // ? 自定義的函數(shù)建議放在 return 部分的后面 function getInitials() { /*...*/ }}export default Article;
難道return不應(yīng)該放在函數(shù)的最后嗎?其實(shí)不然,對(duì)于常規(guī)函數(shù),肯定是要將return放在最后的。然而,React組件并不是簡(jiǎn)單的函數(shù),它們通常包含具有各種用途的嵌套函數(shù),例如事件處理程序。最后的return語(yǔ)句以及前面的一堆其他函數(shù),實(shí)際上阻礙了代碼的閱讀,使得很難找到組件渲染的內(nèi)容:
當(dāng)然,可以根據(jù)個(gè)人喜好來(lái)決定函數(shù)定義的位置。如果將函數(shù)放在return的下方,那么如果想要使用箭頭函數(shù)來(lái)自定義函數(shù),那就只能使用var來(lái)定義,因?yàn)閘et和const不存在變量提升,不能在定義的箭頭函數(shù)之前使用它。
在處理大型 JSX 代碼時(shí),將某些內(nèi)容塊提取為單獨(dú)的函數(shù)來(lái)渲染組件的一部分是很有幫助的,類似于將大型函數(shù)分解為多個(gè)較小的函數(shù)。
function Article(props: Props) { // ... return ( <article> <h1>{props.title}</h1> {renderBody()} {renderFooter()} </article> ); function renderBody() { return /* article body JSX */; } function renderFooter() { return /* article footer JSX */; }}export default Article;
那為什么不將它們提取為組件呢?關(guān)于部分渲染函數(shù)其實(shí)是存在爭(zhēng)議的,一種說(shuō)法是要避免從組件內(nèi)定義的任何函數(shù)中返回 JSX,另一種說(shuō)法是將這些函數(shù)提取為單獨(dú)的組件。
function Article(props: Props) { // ... return ( <article> <h1>{props.title}</h1> <ArticleBody {...props} /> <ArticleFooter {...props} /> </article> );}export default Article;function ArticleBody(props: Props) {}function ArticleFooter(props: Props) {}
在這種情況下,就必須手動(dòng)將子組件所需的局部變量通過(guò)props傳遞。在使用 TypeScript 時(shí),我們還需要為組件的props定義額外的類型。最終代碼就會(huì)變得臃腫,這就會(huì)導(dǎo)致代碼變得難以閱讀和理解:
function Article(props: Props) { const [status, setStatus] = useState(""); return ( <article> <h1>{props.title}</h1> <ArticleBody {...props} status={status} /> <ArticleFooter {...props} setStatus={setStatus} /> </article> );}export default Article;interface BodyProps extends Props { status: string;}interface FooterProps extends Props { setStatus: Dispatch<SetStateAction<string>>;}function ArticleBody(props: BodyProps) {}function ArticleFooter(props: FooterProps) {}
這些單獨(dú)的組件不可以重復(fù)使用,它們僅被它們所屬的組件使用,單獨(dú)使用它們是沒(méi)有意義的。因此,這種情況下,還是建議將部分 JSX 提取成渲染函數(shù)。
React 組件通常會(huì)包含事件處理函數(shù),它們是嵌套函數(shù),通常會(huì)更改組件的內(nèi)部狀態(tài)或調(diào)度操作以更新組件的狀態(tài)。
另一類嵌套函數(shù)就是閉包,它們是讀取組件狀態(tài)或props的不純函數(shù),用于構(gòu)建組件邏輯。
function Article(props: Props) { const [email, setEmail] = useState(""); return ( <article> {/* ... */} <form onSubmit={subscribe}> <input type="email" value={email} onChange={setEmail} /> <button type="submit">Subscribe</button> </form> </article> ); // 事件處理 function subscribe(): void { if (canSubscribe()) { // 發(fā)送訂閱請(qǐng)求 } } function canSubscribe(): boolean { // 基于 props 和 state 的邏輯 }}export default Article;
最后就是純函數(shù),我們可以將它們放在組件文件的底部,在 React 組件之外:
function Article(props: Props) { // ... // ? 純函數(shù)不應(yīng)該放在組件之中 function getInitials(str: string) {}}export default Article;
function Article(props: Props) { // ...}// ? 純函數(shù)應(yīng)該放在組件之外function getInitials(str: string) {}export default Article;
首先,純函數(shù)沒(méi)有依賴項(xiàng),如 props、狀態(tài)或局部變量,它們接收所有依賴項(xiàng)作為參數(shù)。這意味著可以將它們放在任何地方。但是,將它們放在組件之外還有其他原因:
下面是一個(gè)完整的典型 React 組件示例。由于重點(diǎn)是文件的結(jié)構(gòu),因此省略了實(shí)現(xiàn)細(xì)節(jié)。
// 1?? 導(dǎo)入依賴項(xiàng)import React from "react";import { Tag } from "./tag";import styles from "./article.module.scss";// 2?? 靜態(tài)定義const MAX_READING_TIME = 10;interface Props { id: number; name: string; title: string; meta: Metadata;}// 3?? 組件定義function Article(props: Props) { // 4?? 變量定義 const router = useRouter(); const theme = useTheme(); const { id, title, content, onSubscribe } = props; const { image, author, date } = meta; const [email, setEmail] = React.useState(""); const [showMenu, toggleMenu] = React.useState(false); const summary = React.useMemo(() => getSummary(content), [content]); const initials = getInitials(author); const formattedDate = getDate(date); // 5?? effects React.useEffect(() => { // ... }, []); // 6?? 渲染內(nèi)容 return ( <article> <h1>{title}</h1> {renderBody()} <form onSubmit={subscribe}> {renderSubscribe()} </form> </article> ); // 7?? 部分渲染 function renderBody() { /*...*/ } function renderSubscribe() { /*...*/ } // 8?? 局部函數(shù) function subscribe() { /*...*/ }}// 9?? 純函數(shù)function getInitials(str: string) { /*...*/ }export default Article;
本文鏈接:http://www.tebozhan.com/showinfo-26-51233-0.html如何設(shè)計(jì)更優(yōu)雅的 React 組件?
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。郵件:2376512515@qq.com
上一篇: C語(yǔ)言中的柔性數(shù)組解析