• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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 };

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Typescript方法重载实现系列二发布时间:2022-07-18
下一篇:
react:typescriptinterfaceuseStateissue发布时间:2022-07-18
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap