對於一些可能被多處引用的功能模塊,建議提煉成業務組件統一管理。這些組件一般有以下特徵:
- 只負責一塊相對獨立,穩定的功能;
- 沒有單獨的路由配置;
- 可能是純靜態的,也可能包含自己的 state,但不涉及 dva 的數據流,僅受父組件(通常是一個頁面)傳遞的參數控制。
下面以一個簡單的靜態組件爲例進行介紹。假設你的應用中經常需要展現圖片,這些圖片寬度固定,有一個灰色的背景和一定的內邊距,有文字介紹,就像下圖這樣:
你可以用一個組件來實現這一功能,它有默認的樣式,同時可以接收父組件傳遞的參數進行展示。
1. 新建文件
在 src/components
下新建一個以組件名命名的文件夾,注意首字母大寫,命名儘量體現組件的功能,這裏就叫 ImageWrapper
。在此文件夾下新增 js 文件及樣式文件(如果需要),命名爲 index.ts
和 index.less
。
在使用組件時,默認會在
index.ts
中尋找 export 的對象,如果你的組件比較複雜,可以分爲多個文件,最後在index.ts
中統一 export,就像這樣:
// MainComponent.ts
export default ({ ... }) => (...);
// SubComponent1.ts
export default ({ ... }) => (...);
// SubComponent2.ts
export default ({ ... }) => (...);
// index.ts
import MainComponent from './MainComponent';
import SubComponent1 from './SubComponent1';
import SubComponent2 from './SubComponent2';
MainComponent.SubComponent1 = SubComponent1;
MainComponent.SubComponent2 = SubComponent2;
export default MainComponent;
你的代碼大概是這個樣子:
// index.ts
import React from 'react';
import styles from './index.less'; // 按照 CSS Modules 的方式引入樣式文件。
export default ({ src, desc, style }) => (
<div style={style} className={styles.imageWrapper}>
<img className={styles.img} src={src} alt={desc} />
{desc && <div className={styles.desc}>{desc}</div>}
</div>
);
// index.less
.imageWrapper {
padding: 0 20px 8px;
background: #f2f4f5;
width: 400px;
margin: 0 auto;
text-align: center;
}
.img {
vertical-align: middle;
max-width: calc(100% - 32px);
margin: 2.4em 1em;
box-shadow: 0 8px 20px rgba(143, 168, 191, 0.35);
}
到這兒組件就建好了。
2. 使用
在要使用這個組件的地方,按照組件定義的 API 傳入參數,直接使用就好,不過別忘了先引入:
import React from 'react';
import ImageWrapper from '@/components/ImageWrapper'; // @ 表示相對於源文件根目錄
export default () => (
<ImageWrapper src="https://os.alipayobjects.com/rmsportal/mgesTPFxodmIwpi.png" desc="示意圖" />
);