【问题标题】:TypeScript Property 'props' does not existTypeScript 属性“道具”不存在
【发布时间】:2017-11-28 14:51:06
【问题描述】:

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

【问题讨论】:

  • 因为this.props.children 应该由 React 自动设置。这是您访问传递给组件的内容的方式。 {path}
  • 另外constructor (props) { super(props); this.props = props; }会抛出SidebarItem上不存在'props'的错误
  • 您找到答案了吗?我在 tsc v2.3.4 上有同样的问题。你有用 TypeScript 编写 React 类组件的好链接吗?'
  • 不。我放弃了尝试将 TypeScript 与 React 一起使用。

标签: reactjs typescript react-tsx


【解决方案1】:

解决方案是安装 React Types 定义

yarn add -DE @types/react

更多详情来自typescript docstypes repo

顺便说一句,我必须重新启动 vscode 才能正确启动 linting。

【讨论】:

  • 通过添加yarn add @types/react 确认为我工作。
【解决方案2】:

TypeScript 遵循 ES 模块规范,而 React 遵循 CommonJS。 This article touches on that among other things.

像这样导入 React 将解决这个问题:

import * as React from 'react';

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

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

【讨论】:

  • 谢谢雅普。干得好。从 typescript 2.3 升级到 3.2,这解决了 VS 编译器问题。
【解决方案3】:

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

interface SidebarItemProps
{
    children: any
} 

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

More about using React in TypeScript

【讨论】:

    【解决方案4】:

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

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

    或者,如果您的标记越来越大:

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

    【讨论】:

    • 虽然这是有效的,当然也不是一个坏建议,但它并不能真正回答问题。这种解决方案只是避免问题,而不是解决问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    • 1970-01-01
    • 2017-06-03
    • 1970-01-01
    • 2018-05-03
    • 2021-07-04
    • 2023-04-02
    相关资源
    最近更新 更多