---
order: 5
title: 新增業務組件
type: 開發
---
對于一些可能被多處引用的功能模塊,建議提煉成業務組件統一管理。這些組件一般有以下特征:
- 只負責一塊相對獨立,穩定的功能;
- 沒有單獨的路由配置;
- 可能是純靜態的,也可能包含自己的 state,但不涉及 dva 的數據流,僅受父組件(通常是一個頁面)傳遞的參數控制。
下面以一個簡單的靜態組件為例進行介紹。假設你的應用中經常需要展現圖片,這些圖片寬度固定,有一個灰色的背景和一定的內邊距,有文字介紹,就像下圖這樣:
<img src="https://gw.alipayobjects.com/zos/rmsportal/vcRltFiKfHBHFrUcsTtW.png" width="400" />
你可以用一個組件來實現這一功能,它有默認的樣式,同時可以接收父組件傳遞的參數進行展示。
## 新建文件
在 `src/components` 下新建一個以組件名命名的文件夾,注意首字母大寫,命名盡量體現組件的功能,這里就叫 `ImageWrapper`。在此文件夾下新增 js 文件及樣式文件(如果需要),命名為 `index.ts` 和 `index.less`。
> 在使用組件時,默認會在 `index.ts` 中尋找 export 的對象,如果你的組件比較復雜,可以分為多個文件,最后在 `index.ts` 中統一 export,就像這樣:
> ```js
> // 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;
> ```
````
你的代碼大概是這個樣子:
```jsx
// 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>
);
````
```css
// 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);
}
```
到這兒組件就建好了。
## 使用
在要使用這個組件的地方,按照組件定義的 API 傳入參數,直接使用就好,不過別忘了先引入:
```js
import React from 'react';
import ImageWrapper from '@/components/ImageWrapper'; // @ 表示相對于源文件根目錄
export default () => (
<ImageWrapper src="https://os.alipayobjects.com/rmsportal/mgesTPFxodmIwpi.png" desc="示意圖" />
);
```