preface

Hello everyone, MY name is Lin Sanxin. Due to the needs of the work project, I started to use React to develop the project last month. Today, it has been almost a month.

React isn’t new to React

Note: in this article, the Vue version is Vue2 and the React version is React17

JSX and Template

While Vue2 uses Template, as Vue users know, React uses JSX, which is a JavaScript syntax extension that looks a lot like XML.

It has the following advantages:

  • JSX executes faster because it is optimized after being compiled into JavaScript code.
  • It is type-safe and errors can be found during compilation.
  • Using JSX to write templates is much easier and faster.

JSX example: Use the reactdom. render function to render the DOM to the node whose ID is app

// Use the reactdom. render function to render the DOM to the node whose id is app
ReactDOM.render(
  <div>
      <h1>I'm Lin Sanxin</h1>
      <h2>I am a rookie</h2>
      <p>React is a great JavaScript library!</p>
  </div>
  ,
  document.getElementById('app'));Copy the code

React sets the style of elements

React uses an inline style. We can use the hump syntax to set inline styles. React automatically adds px after specifying the element number. The following example demonstrates adding myStyle inline to an h1 element:

function Demo() {

  var myStyle = {
    fontSize: 100./ / the hump method
    color: '#FF0000'
  }

  return <h1 style={myStyle}>Lin sanxin is a rookie</h1>
}
Copy the code

React assigns class to elements

Since JSX is JavaScript, some identifiers like class are not recommended as XML attribute names. Instead, use className for the corresponding attribute.

function Demo() {

  const classes = 'haha heihei xixi'

  return (
    <div>
      <h1 className='haha'>Lin sanxin is a rookie</h1>/ / a single<h1 className='haha heihei'>Lin sanxin is a rookie</h1>/ / multiple<h1 className={classes}>Lin sanxin is a rookie</h1>// Use the value as class</div>)}Copy the code

4. React click events

Click events in Vue are triggered by @click, whereas in JSX they are triggered by onClick

function Demo() {
  const handleClick = () = > {
    console.log('Lin SAN Xin is a rookie')}return (
    <button onClick={handleClick}>Am I</button>)}Copy the code

React changes trigger DOM updates

I use useState in React Hook. This hook is relatively easy to modify constants, but when modifying reference objects or arrays, it requires a shallow copy before overwriting the changes

import { useState } from 'react'

function Demo() {
  const [msg, setMsg] = useState('I'm a rookie')
  const [obj, setObj] = useState({
    name: 'Lin Three Hearts'.food: 'instant noodles'
  })
  const [arr, setArr] = useState([
    { message: 'Lin SAN Xin ah'.id: 1 },
    { message: 'Lin SAN Xin ah ah'.id: 2 },
    { message: 'Lin SAN Xin ah ah ah'.id: 3}])const handleClick = (type: number) = > {
    switch (type) {
      case 1:
        setMsg('Lin SAN Xin is a rookie') // Assign directly
        break;
      case 2: setObj({ ... obj,food: 'Beef meatballs',})/ / shallow copy
        break;
      case 3:
        setArr([...arr, { message: 'Lin SAN Xin aaah aaah'.id: 4}]) // Shallow copy implements push effect
        break; }}return (
    <div>
      <button onClick={()= >Modified MSG handleClick (1)} ></button>
      <button onClick={()= >HandleClick (2)}> Modify obj food</button>
      <button onClick={()= >HandleClick (3)}>arr adds an entry</button>
      <h1>{msg}</h1>
      <p>{' I am ${obj.name} I like to eat ${obj.food} '}</p>
      <ul>
        {
          arr.map(({ message, id }) => {
            return <li key={id}>{message}</li>
          })
        }
      </ul >
    </div>)}Copy the code

6. Life cycle

React hook — useEffect

import { useState, useEffect } from 'react'
function App() {
  const [num, setNum] = useState(1)
  const [count, setCount] = useState(1)
  useEffect(() = > {
    console.log('Hahahaha')})return (
    <div>
      <button onClick={()= >SetNum (num + 1)}</button>
      <button onClick={()= >SetCount (count + 1)}> I count</button>
    </div>)}Copy the code

The second parameter is not passed

 useEffect(() = > {
    console.log('Hahahaha')})Copy the code

When the second useEffect parameter is not passed, the first parameter function is executed when the page is initialized and the data is updated, so the page is initialized with a ha-ha-ha, and then whenever you click change num or change count, a ha-ha-ha is printed

The second argument is passed to an empty array

 useEffect(() = > {
    console.log('Hahahaha')}, [])Copy the code

When useEffect is passed to the second argument [], the first argument function is executed only once at the beginning of the page, regardless of whether you click change num or change count

The second argument is passed to a non-empty array

 / / 1.
 useEffect(() = > {
    console.log('Hahahaha')
 }, [num])
 
 / / 2.
 useEffect(() = > {
    console.log('Hahahaha')
 }, [count])
 
 / / 3.
 useEffect(() = > {
    console.log('Hahahaha')
 }, [num, count])
Copy the code

The useEffect function is executed when the second argument is passed a non-empty array and the page’s original and dependent data is updated. Take the above example:

  • < num > < num > < numHa ha ha ha
  • ② The output will be output again only when the change count button is pressedHa ha ha ha
  • No matter which button is pressed, it will output againHa ha ha ha

Return Clear operation

useEffect(() = > {
    const timeId = setTimeout(() = > console.log('I'm the timer.'), 1000)
    return () = > clearTimeout(timeId)
 })
Copy the code

React performs cleanup operations when components are uninstalled. Effect is executed every time it is rendered. React cleans up the previous effect before executing the current effect.

If you still don’t understand, you can click the button crazy-to see if the sentence will be output many times or only once

React implements V-if & V-else

Vue 中的 v-if & v-else

The V-if directive is used to conditionally render a piece of content. This content will only be rendered if the expression of the directive returns true.

<h1 v-if="show""> </h1>Copy the code

You can also add an “else block” with v-else:

<h1 v-if="show""> </h1><h1 v-else>Oh no 😢</h1>
Copy the code

The React to implement

If you only want to implement v-if, you can use the && logical operator

import { useState } from 'react'
function Demo() {

  const [show, setShow] = useState(false)
  const changeShow = () = >{ setShow(! show) }return (
    <div>
      {show && <h1>Lin sanxin is a rookie</h1>}
      <button onClick={changeShow}>Am I</button>
    </div>)}Copy the code

If you want to implement v-if and V-else, you can use the ternary operators

import { useState } from 'react'
function Demo() {

  const [show, setShow] = useState(false)
  const changeShow = () = >{ setShow(! show) }return (
    <div>
      {show ? <h1>Lin sanxin is a rookie</h1> : <h1>The rookie is Lin Sanxin</h1>}
      <button onClick={changeShow}>Am I</button>
    </div>)}Copy the code

React implements V-show

V – show in Vue

Another option for displaying elements by conditions is the V-show directive. The usage is roughly the same:

<h1 v-show="show"> </h1>Copy the code

The difference is that elements with v-show are always rendered and remain in the DOM. V-show simply toggles the element’s CSS property display.

The React to implement

You just change the display style of the element to make it work

function Demo() {

  / /... Same code
  
  return (
    <div>
      <h1 style={{display: show ? 'block': 'none'}} >Lin sanxin is a rookie</h1>
      <button onClick={changeShow}>Am I</button>
    </div>)}Copy the code

React implements v-for

We can use the V-for directive to render a list based on an array. The V-for directive requires a special syntax of the form item in Items, where items are the source data array and item is the alias of the array element being iterated over.

The v – for Vue

<ul>
  <li v-for="item in items" :key="item.message">
    {{ item.message }}
  </li>
</ul>
Copy the code

The React to implement

JSX allows you to insert arrays into templates that automatically expand all members:

function Demo() {

  const arr = [
    <li key={1}>Lin three heart</li>.<li key={2}>Lin Sanxin ah ah</li>.<li key={3}>Lin Sanxin ah ah ah</li>,]return (
    <ul>
      {arr}
    </ul >
  )
}
Copy the code

But I mostly use the map method of an array to assist in rendering

function Demo() {

  const arr = [
    { message: 'Lin SAN Xin ah'.id: 1 },
    { message: 'Lin SAN Xin ah ah'.id: 2 },
    { message: 'Lin SAN Xin ah ah ah'.id: 3}]return (
    <ul>
      {
        arr.map(({ message, id }) => {
          return <li key={id}>{message}</li>
        })
      }
    </ul >
  )
}
Copy the code

React implements computed

The computed Vue

Whenever name or food changes, maG updates to the corresponding value

<h1>{{msg}}</h1>

computed: { msg() { return I was `The ${this.name}And I love to eatThe ${this.food}`}}Copy the code

The React to implement

React uses the useMemo hook to implement computed effects

import { useState, useMemo } from 'react'
function Demo() {
  const [name, setName] = useState('Lin Three Hearts')
  const [food, setFood] = useState('instant noodles')

  // Implements computed functionality
  const msg = useMemo(() = > I was `${name}And I love to eat${food}`, [name, food]) // Listen for the name and food variables

  const handleClick = (type: number) = > {
    if (type === 1) {
      setName('Rookie')}else if (type === 2) {
      setFood('Beef meatballs')}}return (
    <div>
      <button onClick={()= >HandleClick (1)} > modify the name</button>
      <button onClick={()= >HandleClick (2)} > modify the food</button>
      <h1>{msg}</h1>
    </div>)}Copy the code

React implement Watch

// useWatch.ts
import { useEffect, useRef } from 'react'

type Callback<T> = (prev? : T) = > void
interface Config {
  immdiate: Boolean
}

const useWatch = <T>(data: T, callback: Callback<T>, config: Config = { immdiate: false }) = > {
  const prev = useRef<T>()
  const { immdiate } = config
  const inited = useRef(false)
  const stop = useRef(false)
  useEffect(() = > {
    const execute = () = > callback(prev.current)
    if(! stop.current) {if(! inited.current) { inited.current =true
        immdiate && execute()
      } else {
        execute()
      }
      prev.current = data
    }
  }, [data])

  return () = > stop.current = true
}

export default useWatch
Copy the code

use

import { useState } from 'react'
import useWatch from '/@/hooks/web/useWatch'
function App() {
  const [num, setNum] = useState(1)
  useWatch(num, (pre) = > console.log(pre, num), { immdiate: true })
  return (
    <div>
      <div style={{ color: '#fff' }}>{num}</div>
      <button onClick={()= >SetNum (num + 1)}</button>
    </div>)}Copy the code

conclusion

This year is coming to an end. I wish you all good health and all the best

I am Lin Sanxin, an enthusiastic front-end novice programmer. If you are progressive, like the front end, want to learn the front end, then we can make friends, touch fish ha ha together, or you have the right front end post opportunity, can let me try, that can add my WX –> Meron857287645