TypeScript 属性“道具”不存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44748286/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeScript Property 'props' does not exist
提问by Knight Yoshi
I have this .tsx file
我有这个 .tsx 文件
import React, { Component } from 'react';
export class SidebarItem extends Component {
constructor (props) {
super(props);
}
render () {
return (<li>{this.props.children}</li>);
}
}
However, TypeScript throws this error:
error TS2339: Property 'props' does not exist on type 'SidebarItem'.
但是,TypeScript 会引发此错误:
error TS2339: Property 'props' does not exist on type 'SidebarItem'.
回答by stilllife
The solution is to install the React Types defintions
解决方案是安装 React Types 定义
yarn add -DE @types/react
More details from the typescript docsand from the types repo
On a side note I had to restart vscode for the linting to kick in properly.
附带说明一下,我必须重新启动 vscode 才能正确启动 linting。
回答by Jaap
TypeScript follows the ES-module specification but React follows CommonJS. This article touches on that among other things.
TypeScript 遵循 ES-module 规范,而 React 遵循 CommonJS。 除其他外,本文还涉及这一点。
Importing React like this will fix this problem:
像这样导入 React 将解决这个问题:
import * as React from 'react';
export class SidebarItem extends React.Component {
constructor (props) {
super(props);
}
render () {
return (<li>{this.props.children}</li>);
}
}
回答by SteveKitakis
You can try the following way of writing a React Comp.
您可以尝试以下方式编写 React Comp。
interface SidebarItemProps
{
children: any
}
class SidebarItem extends React.Component<SidebarItemProps, any> {
//your class methods
}
回答by Leone
If your component has no state, you don't have to use a class at all. You can also use a stateless react component (SFC) as answered for this question.
如果您的组件没有状态,则根本不必使用类。您还可以使用无状态反应组件 (SFC) 作为对这个问题的回答。
const MyStatelessComponent : React.StatelessComponent<{}> = props =>
<li>{props.children}</li>;
Or if your markup is getting huge:
或者,如果您的标记越来越大:
const MyStatelessComponent : React.StatelessComponent<{}> = props => {
return <li>{props.children}</li>;
}