【问题标题】:TS2339: Property 'PropTypes' does not exist on type 'typeof React' when porting to TypescriptTS2339:移植到 Typescript 时,类型“typeof React”上不存在属性“PropTypes”
【发布时间】:2018-08-02 22:54:27
【问题描述】:

我目前正在将 javascript/react 项目转换为 typescript/react/redux 项目。

我目前遇到了这个文件的问题:

import React from 'react';
import GoldenLayout from 'golden-layout';
import {Provider} from 'react-redux';
import Default from '../modules/m-Default/Default';

interface GoldenLayoutWrapperProps {}

interface GoldenLayoutWrapperState {}

class GoldenLayoutWrapper extends React.Component <GoldenLayoutWrapperProps, GoldenLayoutWrapperState> {

    public layout;
    static contextTypes = {
        store: React.PropTypes.object.isRequired
    };

    private wrapComponent(Component, store) {
        class Wrapped extends React.Component {
            render () {
                return (
                    <Provider store={store}>
                        <Component {...this.props}/>
                    </Provider>
                )
            }
        }
        return Wrapped;
    }

    componentDidMount() {
        var layout = new GoldenLayout(this.layoutConfig, this.layout);

        layout.registerComponent('Default', this.wrapComponent(Default, this.context.store));
    }

    render() {
        return (
            <div className="golden-layout-wrapper" ref={input => this.layout = input}/>
        )
    }

    private layoutConfig = {}
}

   export default GoldenLayoutWrapper;

当我尝试编译时,出现以下错误:

ERROR in [at-loader] ./src/main/GoldenLayoutWrapper.tsx:18:22 
TS2339: Property 'PropTypes' does not exist on type 'typeof React'.

经过一番搜索,有人建议给contextTypes一个静态修饰符,我尝试过,但问题仍然存在。

可能是什么问题?

【问题讨论】:

  • 你用的是哪个版本的 reactjs?
  • @Aaqib 我正在使用 react 16.0.0

标签: reactjs typescript redux


【解决方案1】:

当您使用 React v16.0.0 时,您需要使用 prop-types,因为它自 React v15.5 起被视为一个单独的库

您可以通过 npm 将其安装为项目依赖项

npm install --save prop-types

然后在你想要使用它的组件内部:

import PropTypes from 'prop-types'; // ES6

你可以直接使用 PropTypes 代替React.PropTypes

你可以阅读更多关于 prop-types Here

【讨论】:

    【解决方案2】:

    在此处查看我的答案以获取完整的详细信息:Cannot read property 'string' of undefined | React.PropTypes | LayoutPropTypes.js

    简而言之,从 React v15.5 开始,React.PropTypes 已被弃用。您需要从 npm 安装 prop-types 包。

    【讨论】:

      猜你喜欢
      • 2020-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-31
      • 2020-10-04
      • 1970-01-01
      • 2022-01-04
      • 2021-01-09
      相关资源
      最近更新 更多