React, Vue, I want them all! React Hook implements 11 basic functions of Vue

preface

Hello, I'm Lin Sanxin. Because of the needs of the work project, last month, I began to use React to develop the project. Today, it's almost a month. I want to share with you how I realized some functions in Vue in React.

As this rookie has not used React for a long time, please pay attention to any defects

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

1. JSX and template

template is used in Vue2, which is known to students who use Vue. JSX is used in React, which is a JavaScript syntax extension that looks like XML.

It has the following advantages:

  • JSX executes faster because it is optimized after compiling into JavaScript code.
  • It is type safe and errors can be found during compilation.
  • Writing templates using JSX is easier and faster.

JSX example: use the ReactDOM.render function to render the DOM to the node with id app

// Use the ReactDOM.render function to render the DOM to the node with id app
ReactDOM.render(
  <div>
      <h1>I'm Lin Sanxin</h1>
      <h2>I'm a rookie</h2>
      <p>React It's a very good one JavaScript library!</p>
  </div>
  ,
  document.getElementById('app')
);

2. Set style for element in React

React uses inline styles. We can use   Hump method   Syntax to set the inline style. React will be automatically added after specifying the element number   px  . The following example demonstrates   h1   Element addition   myStyle   Inline style:

function Demo() {

  var myStyle = {
    fontSize: 100, // Hump method
    color: '#FF0000'
  }

  return <h1 style={myStyle}>Lin Sanxin is a rookie</h1>
}

3. Set class for element in React

Because JSX is JavaScript, some identifiers are like   class   Not recommended as an XML attribute name. As an alternative, use   className as the corresponding attribute.

function Demo() {

  const classes = 'haha heihei xixi'

  return (
    <div>
      <h1 className='haha'>Lin Sanxin is a rookie</h1> // single
      <h1 className='haha heihei'>Lin Sanxin is a rookie</h1> // Multiple
      <h1 className={classes}>Lin Sanxin is a rookie</h1> // Use value as class
    </div>
  )
}

4. Click events in React

Click events in Vue are triggered by @ click, while onClick is used in JSX

function Demo() {
  const handleClick = () => {
    console.log('Lin Sanxin is a rookie')
  }

  return (
    <button onClick={handleClick}>Point me</button>
  )
}

5. Modify the value in React to trigger DOM update

I use the useState in React hook. This hook is relatively simple when modifying constants, but when modifying reference objects or arrays, you need to make a shallow copy first and then overwrite it

import { useState } from 'react'

function Demo() {
  const [msg, setMsg] = useState('I'm a rookie')
  const [obj, setObj] = useState({
    name: 'Lin Sanxin',
    food: 'Instant noodles'
  })
  const [arr, setArr] = useState([
    { message: 'Lin Sanxin', id: 1 },
    { message: 'Lin Sanxin', id: 2 },
    { message: 'Lin Sanxin', id: 3 }
  ])
  const handleClick = (type: number) => {
    switch (type) {
      case 1:
        setMsg('Lin Sanxin is a rookie') // Direct assignment
        break;
      case 2:
        setObj({ ...obj, food: 'Beef balls', }) // Shallow copy
        break;
      case 3:
        setArr([...arr, { message: 'Lin Sanxin', id: 4}]) // Shallow copy for push effect
        break;
    }
  }

  return (
    <div>
      <button onClick={() => handleClick(1)}>modify msg</button>
      <button onClick={() => handleClick(2)}>modify obj of food</button>
      <button onClick={() => handleClick(3)}>arr Add an item</button>
      <h1>{msg}</h1>
      <p>{`I am ${obj.name}I love eating ${obj.food}`}</p>
      <ul>
        {
          arr.map(({ message, id }) => {
            return <li key={id}>{message}</li>
          })
        }
      </ul >
    </div>
  )
}

6. Life cycle

hook using React -- useEffect

import { useState, useEffect } from 'react'
function App() {
  const [num, setNum] = useState(1)
  const [count, setCount] = useState(1)
  useEffect(() => {
    console.log('Ha ha ha ha')
  })
  return (
    <div>
      <button onClick={() => setNum(num + 1)}>Click me to modify num</button>
      <button onClick={() => setCount(count + 1)}>Point me count</button>
    </div>
  )
}

The second parameter is not passed

 useEffect(() => {
    console.log('Ha ha ha ha')
 })

When the second parameter of useEffect is not transmitted, the first parameter function will be executed when the page is initialized and the data is updated. Therefore, ha ha ha ha will be output when the initial page is displayed, and then ha ha ha ha will be output when you click the modify num or modify count button

The second parameter is an empty array

 useEffect(() => {
    console.log('Ha ha ha ha')
 }, [])

When the second parameter of useEffect is passed to [], the first parameter function will be executed only at the beginning of the page, that is, only once. No matter you click the modify num or modify count button, this function will not be executed

The second parameter is passed to a non empty array

 // ①
 useEffect(() => {
    console.log('Ha ha ha ha')
 }, [num])
 
 // ②
 useEffect(() => {
    console.log('Ha ha ha ha')
 }, [count])
 
 // ③
 useEffect(() => {
    console.log('Ha ha ha ha')
 }, [num, count])

When the second parameter of useEffect is passed to a non empty array and the initial and dependent data of the page are updated, the first parameter function will be executed. For example, the above example:

  • ① Only when you press the modify num button can you output ha ha again
  • ② . only when you press the modify count button will you output ha ha again
  • ③ No matter which button is pressed, it will be output again ha ha

return clear operation

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

React will clear the components when they are unloaded. Effect is executed every time you render. React clears the previous effect before executing the current effect.

If you don't understand it, you can crazy click the button to see if I am a timer. This sentence will be output many times or only once, and you suddenly realize it

7. Implementation of V-IF & v-else in React

V-IF & v-else in Vue

v-if   Instruction is used to conditionally render a piece of content. This content will only be rendered when the expression of the instruction returns the true value.

<h1 v-if="show">Lin Sanxin is a rookie</h1>

It can also be used   v-else   Add an else block:

<h1 v-if="show">Lin Sanxin is a rookie</h1>
<h1 v-else>Oh no 😢</h1>

Implementation in React

If you only want to implement v-if, you can use & & logical 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>}
      <button onClick={changeShow}>Point me</button>
    </div>
  )
}

If you want to implement v-if and v-else, you can use the ternary 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> : <h1>The rookie is Lin Sanxin</h1>}
      <button onClick={changeShow}>Point me</button>
    </div>
  )
}

8. Implementation of v-show in React

v-show in Vue

Another option for displaying elements based on conditions is   v-show   Instructions. The usage is roughly the same:

<h1 v-show="show">Lin Sanxin is a rookie</h1>

The difference is with   v-show   Elements of are always rendered and retained in the DOM. v-show   Simply switch the CSS property of the element   display.

Implementation in React

In fact, it is to change the display style of the element to achieve the effect

function Demo() {

  // ... the same code
  
  return (
    <div>
      <h1 style={{display: show ? 'block': 'none'}}>Lin Sanxin is a rookie</h1>
      <button onClick={changeShow}>Point me</button>
    </div>
  )
}

9. Implementation of v-for in React

We can use   v-for   Instruction renders a list based on an array. v-for   Instructions need to be used   item in items   Special grammar of form, where   items   Is an array of source data, and   item   Is the alias of the array element being iterated.

v-for in Vue

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

Implementation in React

JSX allows you to insert an array into a template. The array will automatically expand all members:

function Demo() {

  const arr = [
    <li key={1}>Lin Sanxin</li>,
    <li key={2}>Lin Sanxin</li>,
    <li key={3}>Lin Sanxin</li>,
  ]

  return (
    <ul>
      {arr}
    </ul >
  )
}

But in most cases, I use the map method of array to assist in rendering

function Demo() {

  const arr = [
    { message: 'Lin Sanxin', id: 1 },
    { message: 'Lin Sanxin', id: 2 },
    { message: 'Lin Sanxin', id: 3 }
  ]

  return (
    <ul>
      {
        arr.map(({ message, id }) => {
          return <li key={id}>{message}</li>
        })
      }
    </ul >
  )
}

10. Implement computed in React

computed in Vue

Whenever name or food changes, mag will be updated to the corresponding value

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

computed: { msg() { return `I am ${this.name},I love it ${this.food}` } }

Implementation in React

In React, you need to use the hook useMemo to achieve the computed effect

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

  // Implement the function of computed
  const msg = useMemo(() => `I am ${name},I love it ${food}`, [name, food]) // Listen for the variables name and food

  const handleClick = (type: number) => {
    if (type === 1) {
      setName('Vegetable bird')
    } else if (type === 2) {
      setFood('Beef balls')
    }
  }

  return (
    <div>
      <button onClick={() => handleClick(1)}>modify name</button>
      <button onClick={() => handleClick(2)}>modify food</button>
      <h1>{msg}</h1>
    </div>
  )
}

11. Implementing watch in React

// 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

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)}>Point me</button>
    </div>
  )
}

epilogue

This year is coming to an end. I hope you are healthy and everything goes well

I'm Lin Sanxin, an enthusiastic front-end rookie programmer. If you are self-motivated, like the front-end and want to learn from the front-end, we can make friends and fish together. Haha, or if you have a suitable front-end job opportunity, you can let me try it. You can add my Wx -- > meron857287645

Tags: Javascript Front-end ECMAScript React Vue.js

Posted on Sat, 04 Dec 2021 01:46:45 -0500 by romanali