ant design pro (五)新增業務組件


一、概述

參看地址:https://pro.ant.design/docs/new-component-cn

  對於一些可能被多處引用的功能模塊,建議提煉成業務組件統一管理。這些組件一般有以下特征:

    •   只負責一塊相對獨立,穩定的功能;

    •   沒有單獨的路由配置;

    •   可能是純靜態的,也可能包含自己的 state,但不涉及 dva 的數據流,僅受父組件(通常是一個頁面)傳遞的參數控制。

  下面以一個簡單的靜態組件為例進行介紹。假設你的應用中經常需要展現圖片,這些圖片寬度固定,有一個灰色的背景和一定的內邊距,有文字介紹,就像下圖這樣:

  你可以用一個組件來實現這一功能,它有默認的樣式,同時可以接收父組件傳遞的參數進行展示。

二、開發過程

2.1、組件開發

在 src/components 下新建一個以組件名命名的文件夾,注意首字母大寫,命名盡量體現組件的功能,這里就叫 ImageWrapper。在此文件夾下新增 js 文件及樣式文件(如果需要),命名為 index.js 和 index.less

在使用組件時,默認會在 index.js 中尋找 export 的對象,如果你的組件比較復雜,可以分為多個文件,最后在 index.js 中統一 export,就像這樣:

// MainComponent.js
export default ({ ... }) => (...);

// SubComponent1.js
export default ({ ... }) => (...);

// SubComponent2.js
export default ({ ... }) => (...);

// index.js
import MainComponent from './MainComponent';
import SubComponent1 from './SubComponent1';
import SubComponent2 from './SubComponent2';

MainComponent.SubComponent1 = SubComponent1;
MainComponent.SubComponent2 = SubComponent2;
export default MainComponent;

其中index.js內容

// index.js
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內容

// 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.2、使用組件

在要使用這個組件的地方,按照組件定義的 API 傳入參數,直接使用就好,不過別忘了先引入:

import React from 'react';
import ImageWrapper from '../../components/ImageWrapper';  // 注意保證引用路徑的正確

export default () => (
  <ImageWrapper
    src="https://os.alipayobjects.com/rmsportal/mgesTPFxodmIwpi.png"
    desc="示意圖"
  />
);

如果放在上一節內容中

import React, {Component} from 'react';
import {Link} from 'dva/router';
import ImageWrapper from '../components/ImageWrapper';  // 注意保證引用路徑的正確

export default class NewPage extends Component {

  render() {
    return (
      <div>
        頁面內容
      </div>,
      <ImageWrapper src="https://os.alipayobjects.com/rmsportal/mgesTPFxodmIwpi.png" desc="示意圖" />
    );
  }
}

.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM