I have this .tsx
file:
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'.
The solution is to install the React Types defintions
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.
TypeScript follows the ES-module specification but React follows CommonJS. This article touches on that among other things .
Importing React like this will fix this problem:
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.
interface SidebarItemProps
{
children: any
}
class SidebarItem extends React.Component<SidebarItemProps, any> {
//your class methods
}
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 .
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>;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.