在类组件上无法识别 React 的 PropTypes 导入

问题描述

我已经通过 npm 模块安装了 PropTypes,下面是代码的简化版本。有谁知道为什么我无法在我的班级上访问 .propType ?

import React from 'react';
import PropTypes from 'prop-types';
import { DataGrid } from 'devextreme-react';

class MyComponent extends React.Component {
    constructor(props: { dataSource?: any[] }) {
        super(props);
    }

    render(): JSX.Element {
        return (
            <DataGrid dataSource={[]}>
            </DataGrid>
        );
    }
}

MyComponent.propTypes = {
    dataSource: PropTypes.array
};

export default MyComponent;

enter image description here

解决方法

我确定您的代码没问题,只需重新启动您的 vscode。发生这种情况。

您可以通过以下方式检查 propTypes 是否正常工作:

MyComponent.propTypes = {
    dataSource: PropTypes.array,testError: 1
};

您将在控制台中收到一条消息

Warning: Failed prop type: MyComponent: prop type `testErrors` is invalid; it must be a function,usually from the `prop-types` package,but received `number`.
    in MyComponent (created by App)
    in App

https://stackblitz.com/edit/react-ts-koxotz?file=MyComponent.tsx