提问者:小点点

TypeScript属性道具不存在


我有这个. 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'.

共3个答案

匿名用户

解决方案是安装React类型定义

yarn add -DE @types/react

来自typescript文档和类型repo的更多详细信息

另一方面,我必须重新启动vscode,以使线绳正常工作。

匿名用户

TypeScript遵循ES-模块规范,但React遵循的是通用JS。这篇文章谈到了这一点。

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

import * as React from 'react';

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

    render () {
        return (<li>{this.props.children}</li>);
    }
}

匿名用户

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

interface SidebarItemProps
{
    children: any
} 

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

有关在TypeScript中使用React的详细信息