如何为 React PropTypes 使用 typescript jsdoc 注释

新手上路,请多包涵

在使用 TypeScript 定义 React 组件时,我们可以这样写:

 class SomeComponent extends React.Component<PropInterface, StateInterface> {
  // ...
}

有没有一种方法可以使用 jsdoc 注释 进行等效操作并检查 props 类型。

原文由 lorefnon 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 587
2 个回答

我更喜欢以下形式(es2015 + @types/react ):

 /**
 * @typedef {object} Props
 * @prop {string} className
 * @prop {number} numberProp
 *
 * @extends {Component<Props>}
 */
export default class SomeComponent extends Component {
    render() {
        return (
            <div className={this.props.className}>
                {this.props.numberProp}
            </div>
        );
    }

}

原文由 artin 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果有人正在寻找替代解决方案。关于这个 打字稿问题,你也可以这样实现。

 import React, { Component } from 'react';
import PropTypes from 'prop-types';

/**
 * @augments {Component<{onSubmit:function, text:string}>}
 * @param {object} event - Input event
 * @return {React.ReactElement} - React component
*/
class Test extends Component {
  handleInput = (event) => {
    event.preventDefault();
    this.props.onSubmit(event.target.value);
  };

  render() {
    const { text } = this.props;
    return <div>Hello, property :O {text}</div>;
  }
}

Test.propTypes = {
  onSubmit: PropTypes.func.isRequired,
  text: PropTypes.string.isRequired,
};

export default Test;

原文由 datoml 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题