zoukankan      html  css  js  c++  java
  • [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 };
  • 相关阅读:
    [BZOJ4199][NOI2015]品酒大会
    [BZOJ4198][Noi2015]荷马史诗
    [BZOJ4197][Noi2015]寿司晚宴
    [BZOJ4196][NOI2015]软件包管理器
    2016-11-15NOIP模拟赛
    2016.6.30模拟赛
    BZOJ3672: [Noi2014]购票
    UOJ#191. 【集训队互测2016】Unknown
    第四届CCF软件能力认证(CSP2015) 第五题(最小花费)题解
    bzoj3926: [Zjoi2015]诸神眷顾的幻想乡 对[广义后缀自动机]的一些理解
  • 原文地址:https://www.cnblogs.com/Answer1215/p/15750753.html
Copyright © 2011-2022 走看看