React 和 JSDoc - 如何正确记录 React 组件?

问题描述 投票:0回答:2

我正在记录我的 React Native 组件,但我不知道如何正确执行。

对于文档生成,我使用 jsdoc/better-docs,据说它能够收集您在

PropTypes
上留下的评论并将其包含在文档中。但是...由于不兼容问题,无法在 React Native 中执行此策略,因此,
PropTypes
未包含在文档中

如何使用 JSDOC 记录此 React 组件?

/**
 * ??
 */
function Cat({ name, color = "#000" }) {
  return <View />;
}

Cat.propTypes = {
  name: PropTypes.string.isRequired,
  color: PropTypes.string,
};

我正在做以下事情:

/**
 * The cat properties.
 *
 * @typedef {object} Props
 * @property {string} name - The cat name.
 * @property {string} [color="#000"] - The cat color.
 */

/**
 * Cat component.
 *
 * @type {React.FC<Props>}
 * @returns {React.ReactElement} The cat.
 */
function Cat({ name, color = "#000" }) {
  return <View />;
}

Cat.propTypes = {
  /** The cat name. */
  name: PropTypes.string.isRequired,

  /** The cat color. */
  color: PropTypes.string,
};

但是我感觉 prop-types 添加类型定义后就没用了(?)。

如何记录你的 React 组件?

javascript reactjs react-native jsdoc
2个回答
8
投票

方法是使用

InferProps
中的
prop-types
。此方法仅适用于 TypeScript :( 而且我没有使用它...相反,我在我的项目中结合了 JSDoc 和 PropTypes,以在开发体验中获得一些“打字稿行为”并自动生成我的文档。

但是有一个无需 TypeScript 的解决方法

只需按照我在此处描述的方式配置您的 JSDoc:JSDoc - 重用类型定义错误(找不到名称“类型名称”)

现在,在您的代码中,只需执行以下操作:

components/cat/propTypes.js:

...

export const CatPropTypes = {
   /** The cat data. */
   data: CatDataShape,
   /** The cat name. */
   name: PropTypes.string.isRequired,
   /** The cat color. */
   color: PropTypes.string,
};

组件/cat/Cat.js

import React from "react";
import { View } from "react-native";
import { InferProps } from "prop-types";

import { CatPropTypes } from "./propTypes"; // <-----

/**
 * Cat component.
 *
 * @type {React.FC<InferProps<import("./propTypes").CatPropTypes>>} <---- JSDoc is in TypeScript mode! FANTASTIC! :D
 * @returns {React.ReactElement} The cat.
 */
function Cat({ name, color = "#000" }) {
  return <View />;
}

Cat.propTypes = CatPropTypes; // <-----

现在一切都很顺利,没有理由维护无用的 JSDoc typedef! :DDDDDD


0
投票

没有 prop.types 可以做到吗?如何使用 JSDoc 定义组件?

© www.soinside.com 2019 - 2024. All rights reserved.