【问题标题】:React and JSDoc - How to document a React component properly?React 和 JSDoc - 如何正确记录 React 组件?
【发布时间】:2022-02-23 05:55:00
【问题描述】:

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

对于文档生成,我使用的是 jsdoc/better-docs,据说它能够收集您留在 PropTypes 上的 cmets 并将它们包含在文档中。但是...由于不兼容问题,无法在 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 没用了。

你如何记录你的反应组件?

【问题讨论】:

  • 另外,如果我在 JSDoc 中使用 complete 类型定义,并且(对于同一个组件)在component.propTypes 中使用简单的PropTypes.object,我会感到很烦linter 警告,这让我怀疑 jsdoc 和 proptypes 的并行使用。

标签: javascript reactjs react-native jsdoc


【解决方案1】:

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

但是有一个没有打字稿的解决方法

只需按照我在此处的描述配置您的 JSDoc:JSDoc - reusing type definitions error (cannot find name ‘type name’)

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

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,
};

components/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 类型定义! :DDDDDD

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-17
    • 2017-01-08
    • 1970-01-01
    • 2020-08-10
    • 2021-02-20
    相关资源
    最近更新 更多