TypeScript属性'props'不存在

Kni*_*shi 8 typescript react-jsx

我有这个.tsx文件

import React, { Component } from 'react';

export class SidebarItem extends Component {
    constructor (props) {
        super(props);
    }

    render () {
        return (<li>{this.props.children}</li>);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,TypeScript会抛出此错误: error TS2339: Property 'props' does not exist on type 'SidebarItem'.

sti*_*ife 11

解决方案是安装React Types定义

yarn add -DE @types/react
Run Code Online (Sandbox Code Playgroud)

来自typescript文档类型repo的更多细节

在旁注中我不得不重新启动vscode以使linting正确启动.


小智 6

您可以尝试以下方式编写 React Comp。

interface SidebarItemProps
{
    children: any
} 

class SidebarItem extends React.Component<SidebarItemProps, any> { 
    //your class methods 
}
Run Code Online (Sandbox Code Playgroud)

有关在 TypeScript 中使用 React 的更多信息


Jaa*_*aap 6

TypeScript遵循ES模块规范,但是React遵循CommonJS。 本文涉及其他内容

这样导入React将解决此问题:

import * as React from 'react';

export class SidebarItem extends React.Component {
    constructor (props) {
        super(props);
    }

    render () {
        return (<li>{this.props.children}</li>);
    }
}
Run Code Online (Sandbox Code Playgroud)