35
头图

Preface

Hello everyone, I am Lin Sanxin, because of the needs of the work project, last month, I started to use React to develop in the project. Today, it has been almost a month. I want to share with you my work on React How to implement some functions in the Vue

Since this rookie has used React there is anything wrong

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

1. JSX and template

Is used in Vue2 template , and this point using Vue's students know, and used in the React is JSX , JSX is a JavaScript syntax looks like the XML extension.

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 the compilation process.
  • Using JSX to write templates is easier and faster.

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

// 使用ReactDOM.render函数,将DOM渲染到对应到id为app的节点下
ReactDOM.render(
  <div>
      <h1>我是林三心</h1>
      <h2>我是菜鸟</h2>
      <p>React是一个很不错的 JavaScript 库!</p>
  </div>
  ,
  document.getElementById('app')
);

2. Set style for elements in React

React uses inline styles. We can use camel case syntax to set the inline style. React will automatically add px after specifying the element number. The following example demonstrates adding myStyle inline style h1

function Demo() {

  var myStyle = {
    fontSize: 100, // 驼峰法
    color: '#FF0000'
  }

  return <h1 style={myStyle}>林三心是菜鸟</h1>
}

3. Set the class to the element in React

Since JSX is JavaScript, some identifiers like class not recommended as XML attribute names. As an alternative, use className corresponding attribute.

function Demo() {

  const classes = 'haha heihei xixi'

  return (
    <div>
      <h1 className='haha'>林三心是菜鸟</h1> // 单个
      <h1 className='haha heihei'>林三心是菜鸟</h1> // 多个
      <h1 className={classes}>林三心是菜鸟</h1> // 使用值来当做class
    </div>
  )
}

4. Click events in React

@click is triggered by Vue , and the click event JSX is onClick

function Demo() {
  const handleClick = () => {
    console.log('林三心是菜鸟')
  }

  return (
    <button onClick={handleClick}>点我</button>
  )
}

5. Modifying values in React triggers DOM updates

I use React hook of useState . This hook is relatively simple to modify the constant, but when modifying the reference object or the array, you need to make a shallow copy of and then overwrite the modification.

import { useState } from 'react'

function Demo() {
  const [msg, setMsg] = useState('我是菜鸟')
  const [obj, setObj] = useState({
    name: '林三心',
    food: '泡面'
  })
  const [arr, setArr] = useState([
    { message: '林三心啊', id: 1 },
    { message: '林三心啊啊', id: 2 },
    { message: '林三心啊啊啊', id: 3 }
  ])
  const handleClick = (type: number) => {
    switch (type) {
      case 1:
        setMsg('林三心是菜鸟') // 直接赋值
        break;
      case 2:
        setObj({ ...obj, food: '牛肉丸', }) // 浅拷贝
        break;
      case 3:
        setArr([...arr, { message: '林三心啊啊啊啊', id: 4}]) // 浅拷贝实现push效果
        break;
    }
  }

  return (
    <div>
      <button onClick={() => handleClick(1)}>修改msg</button>
      <button onClick={() => handleClick(2)}>修改obj的food</button>
      <button onClick={() => handleClick(3)}>arr添加一项</button>
      <h1>{msg}</h1>
      <p>{`我是${obj.name}我喜欢吃${obj.food}`}</p>
      <ul>
        {
          arr.map(({ message, id }) => {
            return <li key={id}>{message}</li>
          })
        }
      </ul >
    </div>
  )
}

6. Life cycle

Use React hook- useEffect

import { useState, useEffect } from 'react'
function App() {
  const [num, setNum] = useState(1)
  const [count, setCount] = useState(1)
  useEffect(() => {
    console.log('哈哈哈哈')
  })
  return (
    <div>
      <button onClick={() => setNum(num + 1)}>点我修改num</button>
      <button onClick={() => setCount(count + 1)}>点我count</button>
    </div>
  )
}

The second parameter is not passed

 useEffect(() => {
    console.log('哈哈哈哈')
 })

When the useEffect not passed, the page initial and data update, the first parameter function will be executed, so at this time, the initial page will output hahahaha, and then no matter you click to modify num or modify count Button, it will also output hahahaha

The second parameter passes an empty array

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

When useEffect second parameter passed [] time, then the first parameter of the function only in will be performed when the initial page, which is executed only once, regardless of your point num modify or amend count button, this function will not be executed

The second parameter is a non-empty array

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

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

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

return clear operation

useEffect(() => {
    const timeId = setTimeout(() => console.log('我是定时器'), 1000)
    return () => clearTimeout(timeId)
 })

React will perform a cleanup operation when the component is uninstalled. The effect is executed every time it is rendered. React will clear the previous effect before executing the current effect.

students who don’t understand yet can click the button crazily to see if the sentence 161b1b236031f8 I am a timer will be output multiple times or only once, and it suddenly dawned on me.

7. Implement 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 piece of content will only be rendered when the expression of the instruction returns a true value.

<h1 v-if="show">林三心是菜鸟</h1>

You can also use v-else add an "else block":

<h1 v-if="show">林三心是菜鸟</h1>
<h1 v-else>Oh no 😢</h1>

Implemented in React

If you only want to achieve 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>林三心是菜鸟</h1>}
      <button onClick={changeShow}>点我</button>
    </div>
  )
}

If you want to achieve v-if and v-else , you can use ternary operator

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

  const [show, setShow] = useState(false)
  const changeShow = () => {
    setShow(!show)
  }

  return (
    <div>
      {show ? <h1>林三心是菜鸟</h1> : <h1>菜鸟是林三心</h1>}
      <button onClick={changeShow}>点我</button>
    </div>
  )
}

8. Implement v-show in React

V-show in Vue

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

<h1 v-show="show">林三心是菜鸟</h1>

The difference is v-show will always be rendered and remain in the DOM. v-show simply toggles the element's CSS property display .

Implemented in React

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

function Demo() {

  // ...一样的代码
  
  return (
    <div>
      <h1 style={{display: show ? 'block': 'none'}}>林三心是菜鸟</h1>
      <button onClick={changeShow}>点我</button>
    </div>
  )
}

9. Implement v-for in React

We can use the v-for instruction to render a list based on an array. v-for instruction needs to use a special syntax of the form item in items items is the source data array, and item alias of the array element to be iterated.

V-for in Vue

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

Implemented in React

JSX allows inserting an array in the template, and the array will automatically expand all members:

function Demo() {

  const arr = [
    <li key={1}>林三心啊</li>,
    <li key={2}>林三心啊啊</li>,
    <li key={3}>林三心啊啊啊</li>,
  ]

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

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

function Demo() {

  const arr = [
    { message: '林三心啊', id: 1 },
    { message: '林三心啊啊', id: 2 },
    { message: '林三心啊啊啊', id: 3 }
  ]

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

10. Implement computed in React

Computed in Vue

As long as name or food changes, mag will be updated to the corresponding value

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

computed: { msg() { return `我是${this.name},我爱吃${this.food}` } }

Implemented in React

In React, you need to useMemo the hook computed to achieve the effect of 061b1b236033ca

import { useState, useMemo } from 'react'
function Demo() {
  const [name, setName] = useState('林三心')
  const [food, setFood] = useState('泡面')

  // 实现computed的功能
  const msg = useMemo(() => `我是${name},我爱吃${food}`, [name, food]) // 监听name和food这两个变量

  const handleClick = (type: number) => {
    if (type === 1) {
      setName('大菜鸟')
    } else if (type === 2) {
      setFood('牛肉丸')
    }
  }

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

11. Implement 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)}>点我</button>
    </div>
  )
}

Concluding remarks

This year is almost over, I hope everyone is healthy and all the best

I am Lin Sanxin, an enthusiastic front-end rookie programmer. If you are motivated, like the front-end, and want to learn the front-end, then we can make friends and fish together haha, or if you have a suitable front-end job opportunity, let me try the

image.png


Sunshine_Lin
2.1k 声望7.1k 粉丝