javascript - 如何获得类型化 react 组件属性的代码完成?

标签 javascript reactjs mobx-state-tree

我正在使用 react 和 mobx-state-tree,我使用 @inject 将商店注入(inject)我的组件。所以最后我通过组件内部的 this.props.uiStore 访问商店。

不幸的是,Visual Studio Code 无法推断我的商店类型,因此我没有任何属性的代码完成。 我想知道我是否可以为此使用 jsDoc(因为它非常适用于方法),但找不到方法。 我在想一些类似的事情:

export default class DeviceMirror extends React.Component {
  /**
   * @namespace
   * @property {object}  props
   * @property {UiStore}  props.uiStore
   */
  props

但它不起作用。

最佳答案

您可以使用 JSDoc 使 Visual Studio Code 正确推断 React 组件 Prop ,诀窍是使用 @extends {Component<{type def for props}, {type def for state}>}} :

文件:store.js(这只是一个示例文件,用于演示智能感知如何捕捉定义,但任何对象、类、类型定义,甚至可能是 json 都可以。如果你可以导入它并反射(reflect)它,你可以将它链接到组件 Prop )

    class CustomClass {
        // ...
    }
    // Note: exporting an object would also do
    export default class UiStore {
        /**
         * @type {string} this is a string
         */
        str = null
        /**
         * @type {number} this is a number
         */
        num = null
        /**
         * @type {Date} this is a Date
         */
        dat = Date
        /**
         * @type {CustomClass} this is a CustomClass
         */
        cls = null
    }

文件:test.jsx

    import React, { Component } from 'react';
    import PropTypes from 'prop-types';
    import UiStore from './store';

    /**
     * @typedef Props
     * @prop {UiStore} uiStore
     */

    /**
     * @extends {Component<Props, {}>}}
     */
    export default class DeviceMirror extends Component {
        static propTypes = {
            // not needed for intellisense but prop validation does not hurt
            uiStore: PropTypes.instanceOf(UiStore),
        }
        /**
         * @param {Props} props - needed only when you don't write this.props....
         */
        constructor(props) {
            super(props);
            this.s = props.uiStore.str;
        }
        render() {
            const { uiStore } = this.props;
            return <p>{uiStore.str}</p>;
        }
    }

VSCode 可以使用这种声明并将提供智能感知和代码完成。来自组件文件内部和外部:

screenshot of vscode

关于javascript - 如何获得类型化 react 组件属性的代码完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54941214/

相关文章:

java - 如何为树结构创建 JSON Schema?

javascript - 来自 CryptoJS 和 Python Hashlib 的等效 MD5

css - 如何在 react js 代码中动态更改 css 选择器属性值?

mobx - 在 mobx-state-tree 中异步加载引用的数据

javascript - 转换为 anonymousModel 时出现 mobx-state-tree 错误

javascript - 使用 JavaScript 读取 div 的宽度

javascript - 错误 "Failed to register a ServiceWorker: The document is in an invalid state."是什么意思?

javascript - 从数组返回 "false" bool 值的数量 - MobX 和 React

javascript - 将辅助数据传递给我的第二个回调函数

reactjs - React - 将 child 分成几部分