react从组件中提取proptype、isRequired和defaultProps



我有以下组件:

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)

这将打印一个具有所有propNames的对象作为一个函数。我无法从对象中获取类型。我如何获得proptype(在这个示例字符串中(和";isRequired";从这个组件?我想用它来自动呈现一个具有所有可能的propNames+PropType+isRequired+defaultPropType 的表

您无法通过读取propType属性来检索您要查找的信息。propTypes中的每个项实际上都是一个验证包装函数,它掩盖了实际的类型验证。

有一种方法可以实现你想要的,但它并不特别漂亮。看看这个答案。

您的场景的另一个选项是创建和导出另一个静态属性,该属性包含您需要的信息。然后创建一个实用程序方法,将您的属性数据映射到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对象并添加自己的注释,例如:


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对象只是一个例子,可能并没有涵盖所有的用例(

最新更新