Implementation of TypeScript in React Project

  • 2021-11-24 00:33:40
  • OfStack

Catalogue 1. Preface 2. How to use it Stateless component
Stateful component
Controlled component
3. Summary

1. Preface

Using typescript alone does not lead to high learning costs, but most front-end developers rely on the framework for their projects

For example, when used in combination with vue and react, there will be a threshold of 1

To write react code using TypeScript, you need to install @ types/react, @ types/react-dom in addition to the typescript library


npm i @types/react -s
npm i @types/react-dom -s

The reason for using the @ types libraries mentioned above is that many javascript libraries do not provide their own declaration files about TypeScript at present

Therefore, ts doesn't know the types of these libraries and the corresponding exported contents. Here @ types is actually the DefinitelyTyped library in the community, which defines the declarations of most JavaScript libraries on the market at present

Therefore, when downloading the @ types declaration corresponding to the related javascript, you can use the type definition corresponding to the library

2. How to use it

When writing an react project, the most common components used are:

Stateless component Stateful component Controlled component

Stateless component

The main purpose is to show UI, and if js declaration is used, it is as follows:


import * as React from 'react'

export const Logo = props => {
    const { logo, className, alt } = props

    return (
        <img src={logo} className={className} alt={alt} />
    )
}

However, at this time, ts will report an error because the porps type is not defined. At this time, interface interface can be used to define porps, as follows:


import * as React from 'react'

interface IProps {
    logo?: string
    className?: string
    alt?: string
}

export const Logo = (props: IProps) => {
    const { logo, className, alt } = props

    return (
        <img src={logo} className={className} alt={alt} />
    )
}

However, we all know that children attribute exists in props, so it is impossible for us to define one more children in each porps interface, as follows:


interface IProps {
    logo?: string
    className?: string
    alt?: string
    children?: ReactNode
}

A more standard writing method is to use the FC attribute defined in React, and the children type has been defined, as follows:


export const Logo: React.FC<IProps> = props => {
    const { logo, className, alt } = props

    return (
        <img src={logo} className={className} alt={alt} />
    )
}

React. FC explicitly defines the return type, other ways are implicitly derived React. FC provides type checking and automatic completion for static attributes: displayName, propTypes, defaultProps React. FC provides an implicit type for children (ReactElement null)

Stateful component

Can be 1 class component with props and state attributes

If you use typescript declaration, it looks like this:


import * as React from 'react'

interface IProps {
  color: string,
  size?: string,
}
interface IState {
  count: number,
}
class App extends React.Component<IProps, IState> {
  public state = {
    count: 1,
  }
  public render () {
    return (
      <div>Hello world</div>
    )
  }
}

The above-mentioned type definition of props and state through generics, and then you can get better intelligent hints in the compiler when you use them

For the definition of Component generic classes, refer to the type definition file node_modules/@ types/react/index. d. ts for React as follows:


class Component<P, S> {

    readonly props: Readonly<{ children?: ReactNode }> & Readonly<P>;

    state: Readonly<S>;

}

As you can see from the above, the state attribute also defines a readable type to prevent direct calls to this. state to update the state

Controlled component

The characteristic of the controlled component is that the content of the element is controlled by the state state of the component

Because the events inside the component are composite events, they are not equivalent to native events.

For example, an input component modifies the internal state, which is commonly defined as follows:


private updateValue(e: React.ChangeEvent<HTMLInputElement>) {
    this.setState({ itemText: e.target.value })
}

Common Event event object types:

ClipboardEvent < T = Element > Clipboard event object DragEvent < T = Element > Drag and drop event object ChangeEvent < T = Element > Change Event Object KeyboardEvent < T = Element > Keyboard event object MouseEvent < T = Element > Mouse event object TouchEvent < T = Element > Touch event object WheelEvent < T = Element > Roller event object AnimationEvent < T = Element > Animation event object TransitionEvent < T = Element > Transition event object

T receives 1 DOM element type

3. Summary

The above is simply to use typescript in react project, but when writing react project, there are hooks, default parameters, store and so on......

The learning cost of typescript in the framework is relatively high, and it needs to be written constantly to be proficient


Related articles: