[英]TypeScript Property 'props' does not exist
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:但是,TypeScript 会引发此错误:
error TS2339: Property 'props' does not exist on type 'SidebarItem'.
The solution is to install the React Types defintions解决方案是安装 React Types 定义
yarn add -DE @types/react
More details from the typescript docs and from the types repo来自打字稿文档和类型存储库的更多详细信息
On a side note I had to restart vscode for the linting to kick in properly.附带说明一下,我必须重新启动 vscode 才能正确启动 linting。
TypeScript follows the ES-module specification but React follows CommonJS. TypeScript 遵循 ES-module 规范,而 React 遵循 CommonJS。 This article touches on that among other things .
除其他事项外,本文还涉及这一点。
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>);
}
}
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
}
More about using React in TypeScript有关在 TypeScript 中使用 React 的更多信息
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>;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.