1. React Component implementation

The React Component is implemented in two ways: Class and Functional. In earlier versions of React, the Class Component was more powerful, and managed by state management and lifecycle hooks. All of these functions are available in Functional’s Component.

State management can be implemented through useState.

Lifecycle hooks can be implemented with useEffect.

Besides, the implementation of Functional can save some code. Similar constructors can be omitted, but you can choose your favorite way to implement Component according to different application scenarios.

Back to the main body, this article gives you a share of how to use Props and State in React+Typescript scenarios. This article is the second in a series that focuses on the basics of React for beginners.

2. Props

Functions are used to pass data between components, not only types, but also functions. Using Props in the Class and Functional Component is an example of how to use Props in Class and Functional Component.

3. State

State controls the State of the Component, and a change in State recalls the Render method of the Component. For this reason, while both state and props can be used to present data on a page, if you want to interact with data, you must use state.

Note that in the Class Component, setting the initial state for the page must be set directly, and setting the state after the page loads must call the React Api — setState. We’ll see examples of this later.

4. Overall structure of Demo

Refer to repo for this example code:

Gitlab.com/yafeya/reac…

Let’s start with app.tsx

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.scss';
import { Paragraph } from './Paragraph';
import { Image } from './Image';
import { HyperLink } from './HyperLink';
import { Like } from './Like';
import { Clock } from './Clock';

export class App extends Component {

  render(){
    return (
      <div className="App">
        <header className="App-header">
          <Image src={logo} alt="logo"></Image>
          <Paragraph part1="Edit" code="src/App.tsx" part2="and save to reload."></Paragraph>
          <HyperLink href="https://reactjs.org" title="Learn React"></HyperLink>
          <Like count={0} onLike={count= >console.log(count)}></Like>
          <Clock></Clock>
        </header>
      </div>); }}Copy the code

Here we define five components, Image, Paragraph, HyperLink, Like, and Clock. And I’m going to use each of them to show you how to write it.

5. Class Component uses Props

// Paragraph.tsx
import { Component } from "react";

export interface ParagraphProps {
    part1: string;
    part2: string;
    code: string;
}

export class Paragraph extends Component<ParagraphProps.{} > {constructor(props: ParagraphProps){
        super(props);
    }

    render(){
        return (
            <p>
                {this.props.part1} <code>{this.props.code}</code> {this.props.part2}
            </p>)}}Copy the code
// App.tsx
// ...
<Paragraph part1="Edit" code="src/App.tsx" part2="and save to reload."></Paragraph>
// ...
Copy the code

Paragraph is a Component written in Class mode. Its constructor must accept a strongly typed props for receiving parameters. The Paragraph Component takes three arguments from the App Component and calls this.props. Part1, this.props. Part2, and this.props. Code directly on UX.

6. Functional Component uses Props

// Image.tsx
import React from 'react';
import './Image.scss';

export interface ImageProps{
    src: string;
    alt: string;
}

export const Image: React.FC<ImageProps> = (props) = >{
    return (<img src={props.src} className="App-logo" alt={props.alt} />);
};
Copy the code
// App.tsx
// ...
<Image src={logo} alt="logo"></Image>
// ...
Copy the code

Image is a Component written in Functional. It is essential to define strongly typed Props for receiving parameters, but it is noticeably less code than class, mainly because constructor is omitted.

It’s important to note that when called in App, you need to use {} if the parameter to be passed to component is a variable. This is the basic syntax for React.

7. Class Component uses State

import { Component } from "react";

export interface LikeProps{
    count: number;
    onLike(count: number) :void;
}

export interface LikeState{
    count: number;
}

export class Like extends Component<LikeProps.LikeState> {
    constructor(props: LikeProps){
        super(props);
        this.state = {
            count: props.count
        };
    }

    setCount(count: number){
        this.setState({
            count: count
        });
    }

    onClick(){
        let count = this.state.count+1;
        this.setCount(count);
        this.props.onLike(count);
    }

    render(){
        return (
            <div>
                <p>There are {this.state.count} person like you!!</p>
                <button className="btn btn-primary" onClick={()= >this.onClick()}>Like</button>
            </div>); }}Copy the code
// App.tsx
// ...
<Like count={0} onLike={count= >console.log(count)}></Like>
// ...
Copy the code

This component is relatively complex because it accepts props and uses state.

  • Set the initial value for state
    // constructor, must be called this way, otherwise it will cause the page to keep refreshing
    this.state = {
        count: props.count
    };
    Copy the code
  • Change state in the button’s response function
setCount(count: number){
    // State can only be changed through the setState API after the page is loaded
    this.setState({
        count: count
    });
}

onClick(){
    let count = this.state.count+1;
    this.setCount(count);
    this.props.onLike(count);
}
Copy the code
  • The function passed by props is called in the response function of the button

In this case, onClick() calls this.props. OnLike (count) directly, which penalizes the handler set up in the App and prints count in the console.

// App.tsx
// ...
<Like count={0} onLike={count= >console.log(count)}></Like>
// ...
Copy the code

8. Functional Component uses State

import React, { Component, useEffect, useRef, useState } from "react";

export interface ClockState{
    time: Date;
}

export const Clock: React.FC = () = >{
    const [time, setTime] = useState(new Date());
    const clockRef = useRef<HTMLParagraphElement>(null);

    useEffect(() = >{
        setInterval(() = > setTime(new Date()), 1000);
    }, [clockRef]);

    return <p ref={clockRef}>The current time is {time.toLocaleTimeString()}</p>;
};
Copy the code
  • Use in functional ComponentuseStateMethod to initialize state and generate a handler that changes state
    // The type of time will implicitly be the parameter type of useState
    // setTime is the handler that changes the time in state
    // Time changes after each call to setTime.
    const [time, setTime] = useState(new Date());
    Copy the code
  • Use in functional ComponentuseEffectMethod to implementcomponentDidMountThe handler

    Note: useEffect accepts an array of dependencies that call callback when the received parameter is mounted

    useEffect(() = >{
          setInterval(() = > setTime(new Date()), 1000);
      }, [clockRef]);
    Copy the code
  • Use in functional ComponentuseRefMethod to get an htmlElement

9. Operation effect