您可以使用 JSDoc 使 Visual Studio Code 正确推断 React 组件道具,诀窍是使用@extends {Component<{type def for props}, {type def for state}>}}
:
文件:store.js(这只是一个示例文件,用于演示智能感知如何捕获定义,但任何对象、类、类型定义,甚至可能是 json 都可以。如果你可以导入它并反映它,你可以将它链接到组件道具)
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 可以使用这种声明,并将提供智能感知和代码完成。从组件文件的内部和外部: