12

我有这个.tsx文件:

import React, { Component } from 'react';

export class SidebarItem extends Component {
  constructor(props) {
    super(props);
  }
  
  render() {
    return (<li>{this.props.children}</li>);
  }
}

但是,TypeScript 会抛出此错误:

error TS2339: Property 'props' does not exist on type 'SidebarItem'.
4

4 回答 4

14

解决方案是安装 React Types 定义

yarn add -DE @types/react

来自typescript docstypes repo的更多详细信息

在旁注中,我必须重新启动 vscode 才能正确启动 linting。

于 2018-01-15T09:30:27.167 回答
12

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>);
    }
}
于 2018-11-23T18:43:11.207 回答
6

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

interface SidebarItemProps
{
    children: any
} 

class SidebarItem extends React.Component<SidebarItemProps, any> { 
    //your class methods 
}

更多关于在 TypeScript 中使用 React

于 2017-06-25T17:38:27.107 回答
0

如果您的组件没有状态,则根本不必使用类。您还可以使用对此问题的回答的无状态反应组件 (SFC) 。

const MyStatelessComponent : React.StatelessComponent<{}> = props =>
    <li>{props.children}</li>;

或者,如果您的标记变得巨大:

const MyStatelessComponent : React.StatelessComponent<{}> = props => {

    return <li>{props.children}</li>;

}
于 2017-06-26T07:11:16.480 回答