簡體   English   中英

從組件中提取 proptypes、isRequired 和 defaultProps

[英]react extract proptypes, isRequired and defaultProps from component

我有以下組件:

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

const MyComponent = ({ text1, text2 }) => {
    return (
        <div>
            <p>{text1}</p>
            <p>{text2}</p>
        </div>
    )
}
MyComponent.propTypes = {
    text1: PropTypes.string,
    text2: PropTypes.string,
}
MyComponent.defaultPropTypes = {
    text1: 'React',
    text2: 'is cool',
}

export default MyComponent

然后我像這樣導入它

import MyComponent from "./MyComponent";

console.log(MyComponent.propTypes)

這將打印一個 object,所有 propNames 為 function。 我無法從 object 中獲取類型。 如何從此組件中獲取 proptype(在此示例字符串中)和“isRequired”? 我想用它來自動渲染一個包含所有可能的 propNames + PropType + isRequired + defaultPropType 的表

您無法通過讀取 propType 屬性來檢索您要查找的信息。 propTypes 中的每個項目實際上是一個驗證包裝器 function,它掩蓋了實際的類型驗證。

有一種方法可以實現您正在尋找的東西,但它並不是特別漂亮。 看到這個答案

您的方案的另一個選項是使用包含所需信息的組件創建和導出另一個 static 屬性。 然后創建一個實用方法將您的屬性數據 map 轉換為 PropTypes

例如:

// -- utility

const validators = {
    string: PropTypes.string,
    string_required: PropTypes.string.isRequired,
}

const getPropTypesFromValidators = (o) => {
    return Object.entries(MyComponent.validators).reduce((acc, [field, validatorKey]) => {
        return { ...acc, [field]: validators[validatorKey] }
    }, {})
}


/// --- component

const MyComponent = ({ text1, text2 }) => {
    return (
        <div>
            <p>{text1}</p>
            <p>{text2}</p>
        </div>
    )
}
MyComponent.validators = {
    text1: 'string',
    text2: 'string_required',
}

MyComponent.propTypes = getPropTypesFromValidators(MyComponent.validators);

MyComponent.defaultPropTypes = {
    text1: 'React',
    text2: 'is cool',
}

// -- app

console.log(MyComponent.validators);

第二種選擇可能是包裝 PropTypes object 並添加您自己的注釋,例如:


const AnnotatedPropTypes = Object.keys(PropTypes).reduce((acc, key) => {
  const fn = (...args) => PropTypes[key](...args);
  fn.description = key;

  if (typeof PropTypes[key].isRequired === "function") {
    fn.isRequired = (...args) => PropTypes[key].isRequired(...args);
    fn.isRequired.description = `${key} (required)`;
  }

  return { ...acc, [key]: fn };
}, {});

// ---- component

...

MyComponent.propTypes = {
  text1: AnnotatedPropTypes.string,
  text2: AnnotatedPropTypes.string.isRequired,
};


console.log(MyComponent.propTypes.text1.description)

(上面的 AnnotatedPropTypes object 只是一個示例,可能並未涵蓋所有用例)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM