1import React from 'react';
2
3interface Props {
4}
5
6const App: React.FC<Props> = (props) => {
7 return (
8 <div><div/>
9 );
10};
11
12export default App;
1import * as React from 'react';
2
3export interface TestProps {
4 count: number;
5}
6
7export interface TestState {
8 count: number;
9}
10
11class Test extends React.Component<TestProps, TestState> {
12 state = { count:0 }
13 render() {
14 return ( <h2>this is test</h2> );
15 }
16}
17
18export default Test;
1interface IProps {
2}
3
4interface IState {
5 playOrPause?: string;
6}
7
8class Player extends React.Component<IProps, IState> {
9 // ------------------------------------------^
10 constructor(props: IProps) {
11 super(props);
12
13 this.state = {
14 playOrPause: 'Play'
15 };
16 }
17
18 render() {
19 return(
20 <div>
21 <button
22 ref={playPause => this.playPause = playPause}
23 title={this.state.playOrPause} // in this line I get an error
24 >
25 Play
26 </button>
27 </div>
28 );
29 }
30}
1class Test extends Component<PropsType,StateType> {
2 constructor(props : PropsType){
3 super(props)
4 }
5
6 render(){
7 console.log(this.props)
8 return (
9 <p>this.props.whatever</p>
10 )
11 }
12
13};
1// Class Component React TypeScript ( with props and state usage ):
2
3import React, { Component } from 'react';
4
5type Props = { head ?: string , age ?: number };
6
7type State = { num: number };
8
9type DefaultProps = { head : string, age : string }
10/* <Props, State, DefaultProps> tell that
11these initialised types will be used in the class. */
12class Counter extends Component <Props, State, DefaultProps> {
13
14/* Default props appear when no value for the prop
15is present when component is being called */
16
17
18 static defaultProps : DefaultProps = {
19 head: "Heading is Missing",
20 age: "Age is missing",
21 };
22// Always write state above the render() method.
23 state: State = {
24 num: 0,
25 };
26
27 render() {
28
29 const add = () => this.setState({ num: this.state.num + 1 }) ;
30
31 return (
32 <div>
33 <h1> { this.props.head } </h1>
34 <p> Age: { this.props.age } </p> <br />
35 <h3> { this.state.num } </h3>
36 <button onClick={add}>Add 1</button>
37 </div>
38 );
39 }
40}
41
42export default Counter;