[React Typescript 2022] Use TypeScript to Type a React Class Component
typescriptReact to 2022 type Class use Component
2023-09-14 08:59:12 时间
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 Typescript] Discriminated unions in components props
- [Typescript] Convert a js project to typescript
- [Typescript] Scopes and TypeParams
- [Typescript] asserts tips
- [Typescript] Prevent Type Widening of Object Literals with TypeScript's const Assertions
- [Typescript] Create Type From Any Given Data in TypeScript
- [Typescript v3.9] ts-expect-error
- [Typescript] Exclude Properties from a Type in TypeScript (Omit)
- [Typescript 4.9] TypeScript 4.9: satisfies operator
- [Typescript + React] Tip: Use generics in React to make dynamic and flexible components
- [Typescript + React] Tips: Write your own 'PropsFrom' helper to extract props from any React component
- [React Typescript 2022] Type a Radio Button Component in React using TypeScript
- [Typescript] Use the Optional Chaining Operator in TypeScript
- [React Testing] Test your Custom Hook Module with react-hooks-testing-library
- [Typescript Kaop-ts] Use AOP in Vue Components with TypeScript and Kaop-ts
- [TypeScript] Function Overloads in Typescript
- 简单实现ant design pro react typescript(ts) spring boot mybatis mysql前后端登录接口 解决ant design pro登录成功无法跳转的问题
- React(一)react概述、组件、事件
- 实现一个自动生成typescript类型声明的工具