为ReactJS无状态函数编写注释的推荐方法是什么?
假设我有以下代码:
export const LoginForm = ({ submitting, handleSubmit }) => (
<form onSubmit={handleSubmit(submit)}> ...(code)... </form>
));
文档评论应该如何?
我的第一个想法是:
/**
* Form for user login
* @param {bool} submitting Shows if form submitting is in progress
* @param {function} handleSubmit Form submit callback function
*/
但这不正确,因为submitting
和handleSubmit
不是LoginForm
函数的真正参数。它们只是props
参数的键。
另一方面,将props
记录为LoginForm
的参数似乎毫无意义,因为每个反应组件都有props
作为参数,而道具键是函数中最重要的部分。
有官方指引吗? (我没找到任何一个)
我还PropTypes
定义了:
LoginForm.propTypes = {
submitting: PropTypes.bool,
handleSubmit: PropTypes.func.isRequired,
};
也许这是道具相关文档的地方?如果是这样,应该怎么样?那有什么标准吗?
答案 0 :(得分:6)
您可以在属性名称前指定props
对象:
/**
* Form for user login
* @param {object} props Component props
* @param {bool} props.submitting Shows if form submitting is in progress
* @param {function} props.handleSubmit Form submit callback function
*/
export const LoginForm = ({ submitting, handleSubmit }) => (
<form onSubmit={handleSubmit(submit)}> ...(code)... </form>
));
有关详细信息,请参阅Parameters With Properties
部分中的@param Wiki页面。
答案 1 :(得分:1)
我知道我参加这个聚会差不多快三年了。只是添加以供参考。一个可以做到这一点:
/**
* @typedef {Object<string, any>} Props
* @property {boolean} submitting Shows if form submitting is in progress
* @property {function} handleSubmit Form submit callback function
*/
/**
* Form for user login
*
* @type {import('react').FunctionComponentElement<Props>}
*/
export const LoginForm = ({ submitting, handleSubmit }) => (
<form onSubmit={handleSubmit(submit)}> ...(code)... </form>
));
为简便起见,也可以这样做:
/**
* Form for user login
*
* @type {import('react').FunctionComponentElement<{
submitting: boolean,
handleSubmit: function
}>}
*/
export const LoginForm = ({ submitting, handleSubmit }) => (
<form onSubmit={handleSubmit(submit)}> ...(code)... </form>
));
如果在您的IDE中启用了Typescript,则可以避免与此设置一起声明属性类型。
答案 2 :(得分:0)
另一个选项是jsdoc-react-proptypes,其用法如下:
SomeComponent.propTypes = {
/** Function to run after animation completes. */
onStop: PropTypes.func
};
这将为该类创建一个“属性”文档部分,其中大致包含您所期望的内容:
Name Type Attributes Description
onStop <optional> Function to run after animation completes.
我不确定为什么Type
不出现;这是一个很粗糙的库,但是我有同样的问题,发现了这个问题,将不得不对其进行清理。
答案 3 :(得分:0)
我认为您可以使用此
* @property {function(argType1, argType2, argTypeN): void} handleSubmit - The handleSubmit Form submit callback function
返回类型中的void可以用数字或字符串之类的任何数据类型代替。