我正在使用 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 可以使用这种声明并将提供智能感知和代码完成。来自组件文件内部和外部:
关于javascript - 如何获得类型化 react 组件属性的代码完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54941214/