1. 程式人生 > 其它 >React開發可複用元件

React開發可複用元件

技術標籤:reactjs

1、prop型別
(1)如果希望整個引用可以複用元件,關鍵要確保清晰的定義元件及其引數,以便能夠直觀使用。
React提供了一個非常簡單的表達元件介面的強大工具,只要提供元件期望接收的prop名稱與對應的驗證規則即可。

import React from 'react';
import PropTypes from 'prop-types';

export default function Button({text}){
    return <button>{text}</button>
}

Button.propTypes = {
text: PropTypes.string }

如果傳入的text值不是string型別,瀏覽器會報一個警告
在這裡插入圖片描述
(2)物件型別定義,如下定義user物件,name和subName都是string型別

import React from 'react';
import PropTypes from 'prop-types';

export default function Button({text, user}){
    return (
        <div>
            <div>{user.name}</div>
            <
div>{user.subName}</div> <button>{text}</button> </div> ) } Button.propTypes = { text: PropTypes.string, user: PropTypes.shape({ name: PropTypes.string.isRequired, subName: PropTypes.string }).isRequired }

(3)自定義函式校驗,對user物件中age屬性進行校驗,只能大於0與100之間

Button.propTypes = {
    text: PropTypes.string,
    user: PropTypes.shape({
        name: PropTypes.string.isRequired,
        subName: PropTypes.string,
        age:(props, propName) => {
            if (props[propName] < 0 || props[propName] >=100) {
                return new Error(`${propName} must be betwwen 1 and 99`)
            }
            return null
        }
    }).isRequired
}

如果不滿足條件則報錯,如下
在這裡插入圖片描述
(3)基於以上prop型別,元件的邊界已經定義的很清晰了,我們可以進行另一個操作,以便它們更易使用和共享,開發人員能夠充分利用這些公共元件,react-docgen庫可以為元件自動生成文件
首先執行命令npm install --global react-docgen 安裝外掛
再執行命令react-docgen Button.jsx,結果如下,將button的props定義生成了一個json文件,方便其他開發人員閱讀

Button.propTypes = {
    text: PropTypes.string,
    /**
     * 使用者物件
     */
    user: PropTypes.shape({
        /**
         * 使用者名稱稱
         */
        name: PropTypes.string.isRequired,
        subName: PropTypes.string
    }).isRequired
}
{
  "description": "",
  "displayName": "Button",
  "methods": [],
  "props": {
    "text": {
      "type": {
        "name": "string"
      },
      "required": false,
      "description": ""
    },
    "user": {
      "type": {
        "name": "shape",
        "value": {
          "name": {
            "name": "string",
            "description": "使用者名稱稱",
            "required": true
          },
          "subName": {
            "name": "string",
            "required": false
          }
        }
      },
      "required": true,
      "description": "使用者物件"
    }
  }
}

2、邏輯元件與表現元件分離
邏輯元件:
(1)負責渲染對應的表現元件
(2)發起API請求並操作資料
(3)定義事件處理器
表現元件:
(1)負責渲染HTML標記
(2)以props的形式從父元件接收資料
(3)通常寫作無狀態函式式元件
3、高階元件