[React Typescript 2022] Use TypeScript to Type a React Class Component

For older applications, it's likely that you have some Class components. TypeScript works a little differently with these. The React.Component class is a generic class and it takes the props type as its first type argument. We will write out an alias for our props that I'll pass in the type argument space for the class. Child classes can also implement their own varIoUs methods for overriding parent methods, we'll also want to explicitly type the props in our constructor.

 

import * as React from "react";

interface CounterProps {
    initialCount?: number;
    className?: string;
}
interface CounterState {
    count: number;
}
class Counter extends React.Component<CounterProps, CounterState> {
    state: CounterState = {
        count: this.props.initialCount ?? 0,
    };

    constructor(props: CounterProps) {
        super(props);
        this.increment = this.increment.bind(this);
        this.decrement = this.decrement.bind(this);
    }

    shouldComponentUpdate(nextProps: CounterProps, nextState: CounterState) {
        return shallowCompare(this, nextProps, nextState);
    }

    increment() {
        this.setState(({ count: prevCount }) => ({
            count: prevCount + 1,
        }));
    }

    decrement() {
        this.setState(({ count: prevCount }) => ({
            count: prevCount - 1,
        }));
    }

    render() {
        return (
            <div className={this.props.className}>
                <button type="button" onClick={this.decrement} aria-label="Decrement">
                    -
                </button>
                <span>{this.state.count}</span>
                <button type="button" onClick={this.increment} aria-label="Increment">
                    +
                </button>
            </div>
        );
    }
}

export { Counter };

 

相关文章

一、前言 在组件方面react和Vue一样的,核心思想玩的就是组件...
前言: 前段时间学习完react后,刚好就接到公司一个react项目...
前言: 最近收到组长通知我们项目组后面新开的项目准备统一技...
react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...