Back-end development shallow learning react

The blog notes come from learning. The react learning videoshared by Mr. Chai Chai on station b is for learning reference only . The learning video is from station b: Chai Chai_Front-end teacher , video link: Introduction to React (2022 latest on the whole network) _哔哩哔哩_bilibili

Start with react official website   – React (docschina.org)

Table of contents

jsx syntax

jsx expression case

jsx conditional rendering

Style processing in jsx

Creation and rendering of function components

Components and props

function event binding

Pass custom parameters in the event

props read-only

The writing of the arrow function can solve the pointing of this

destructuring assignment

useState

useEffect


jsx syntax

jsx expression case

Grammar: {JS expression} Note that only expressions can be written in this {}, not statements! ! !

Expressions that can be used:

  • string, number, boolean, null, undefined, object ( [] / {} )

  • 1 + 2、'abc'.split('')、['a', 'b'].join('-')

  • fn()

case:

//1.识别我们的常规变量
const name = "react 学习"

//2.原生js中的调用
const getAge = () =>{
  return "永远的18";
}

//3.三元运算符(常用)
const flag  = false;

function App() {
  return (
    <div className="App">
      {name}<br></br>
      {getAge()}<br></br>
      {flag ? '18':'68'}
    </div>
  );
}

export default App;

jsx conditional rendering

Function: Generate an HTML structure according to whether the conditions are met, and render when the conditions are met.

Implementation: can use or 三元运算符逻辑与(&&)运算符

// 来个布尔值
const flag = true
function App() {
  return (
    <div className="App">
      {/* 条件渲染字符串 */}
      {flag ? 'react真有趣' : 'vue真有趣'}
      {/* 条件渲染标签/组件 */}
      {flag ? (<span>this is span</span>) : null}
    </div>
  )
}
export default App

What should we do if we encounter complex multi-branch logic? It is definitely not possible to set triplets in triplets, which will lead to very poor readability of the code.

Principle: Keep the logic in the template as simple as possible. Converge to a function, write branch logic through a special function, and the template is only responsible for calling.

const getTag = (type)=>{
    if(type === 1){
        return <h1>this h1</h1>
    }
    if(type === 2){
        return <h2>this h2</h2>
    }
    if(type === 3){
        return <h3>this h1</h3>
    }
}

function App() {
return (
    <div className="App">
    getTag(1)
    </div>
);
}
  
export default App;

Style processing in jsx

Note: When using style processing, you need to use two {} to wrap, the function of the first {} is to make the second {} recognized as an object, and the second {} is an object, used to write our style attribute.

1. Inline style - style (just bind a style attribute to the element)

function App() {
  return (
    <div className="App">
      <div style={
   
   { color: 'red' }}>this is a div</div>  //所以以后看见两个{}要知道是在干啥
    </div>
  )
}
export default App

2. Inline style - style - better writing method (extract the style as an object)

const styleObj = {
    color:red
}
function App() {
  return (
    <div className="App">
      <div style={ styleObj }>this is a div</div>
    </div>
  )
}
export default App

3. Class name - className (recommended) (just bind a className attribute to the element)

.active{
    color:blue;
}
import './app.css'
function App() {
  return (
    <div className="App">
      <span className='active'>测试类名样式</span>
    </div>
  )
}
export default App

Creation and rendering of function components

Components and props

Components: Components are conceptually similar to JavaScript functions. It takes arbitrary input parameters (aka "props") and returns React elements describing what the page should display.

When the React element is a user-defined component , it converts the attributes (attributes) and subcomponents (children) received by JSX into a single object and passes it to the component. This object is called "props".

First look at a case given by the react official website: the following code will output: Hello Sara

function Welcome(props) {  //自定义组件
  return <h1>Hello, {props.name}</h1>;
}

//如果是类组件 那么使用this来获取
//class Square extends React.Component {
//  render() {
//    return (
//      <button className="square">
//        {this.props.name}
//      </button>
//    );
//  }
//}

const element = <Welcome name="Sara" />;  //在jsx中使用自定义组件 Welcome,并且传了一个属性name给Welcome组件,Welcome组件可以用props来接收使用Welcome组件的jsx中传过来的属性或者是对象
ReactDOM.render(
  element,
  document.getElementById('root')
);

Let's see what happens in this example:

  1. We call ReactDOM.render()the function , passing in <Welcome name="Sara" />as an argument.

  2. React calls Welcomethe component and {name: 'Sara'} passes it in as props .

  3. WelcomeThe component returns <h1>Hello, Sara</h1>a element as a return value.

  4. React DOM efficiently updates the DOM as <h1>Hello, Sara</h1>.

Agreement Description

  1. The name of the component must be capitalized , and react will judge whether it is a component or a normal HTML tag based on this.

  2. The function component must have a return value , and the returned value represents the UI structure of the component; if there is no need to render any content, return null.

  3. Components can be rendered into the page just like HTML tags. A component represents a piece of structural content. For a function component, the rendered content is the return value of the function is the corresponding content.

  4. Use the function name as the component label name, which can appear in pairs or be self-closing.

import React from "react"

//创建函数式组件
function Hello () {
  return <div>hello</div>
}

//类组件的创建和渲染
class HelloCompoent extends React.Component {
  //这个render函数是必须的
  render () {
    return <div>this is class component</div>
  }
}
function App () {
  return (

    <div className="App">
      {/* 渲染hello组件 */}
      <Hello></Hello>

      {/* 渲染类组件 */}
      <HelloCompoent></HelloCompoent>
    </div>
  )
}
export default App

function event binding

  • Syntax on + event name = { event handler (callback function) }, for example:<div onClick={ onClick }></div>

  • Note that react events use camel case naming , such as: onMouseEnter, onFocus

Function event binding:

import React from "react"

//创建函数式组件
function Hello () {
//创建一个事件(相当于一个方法)  这种类似java的lambada表达式的写法是react中声明事件的标准写法,可以避免一些不必要this指向问题
  const clickHandler = () => {
    console.log('函数组件中的事件被触发了')
  }
  //绑定事件
  return <div onClick={clickHandler}>hello</div>
}

function App () {
  return (
    <div className="App">
      {/* 渲染hello组件 */}
      <Hello></Hello>
    </div>
  )
}

export default App

Pass custom parameters in the event

Scenario: We want to pass some custom parameters when an event is triggered, how should we do it?

import React from "react"

//创建函数式组件
function Hello () {
  //创建一个事件(相当于一个方法)
  const clickHandler = (msg) => {
    console.log('函数组件中的事件被触发了', msg)
  }
  //需要在调用的时候传递实参,需要修改函数组件触发的调用方式了  : 改造成箭头函数的调用方式就行
  return <div onClick={()=>clickHandler('this is msg')}> 点击 </div>
  {/*之前的调用方式<div onClick={clickHandler}>点击</div> */}
}
function App () {
  return (

    <div className="App">
      {/* 渲染hello组件 */}
      <Hello></Hello>
    </div>
  )
}
export default App

 What should we do if we want to pass both e and custom parameters?

import React from "react"

//创建函数式组件
function Hello () {
  //创建一个事件(相当于一个方法)
  const clickHandler = (e,msg) => {
    console.log('函数组件中的事件被触发了', e,msg)
  }
  //需要在调用的时候传递实参,需要修改函数组件触发的调用方式了  : 改造成箭头函数的调用方式就行  并且需要注意形参和实参的顺序
  return <div onClick={(e)=>clickHandler(e,'this is msg')}> 点击 </div> {/* 需要先捕获e然后再传递到绑定的事件中*/}
  {/*
  之前不需要传递参数的调用方式<div onClick={clickHandler}>点击</div>
  之前传递一个自定义参数的调用方式:return <div onClick={()=>clickHandler('this is msg')}> 点击 </div> 
  */}
}
function App () {
  return (

    <div className="App">
      {/* 渲染hello组件 */}
      <Hello></Hello>
    </div>
  )
}
export default App

Summarize:

1. Only one additional parameter is required: {clickHandler} -> { () => clickHandler('custom parameter')}

2. Both e and additional custom parameters are required {(e) => clickHandler(e,'custom parameters')}

props read-only

We have briefly explained the function of props in components and props, and here we will introduce the read-only nature of props separately.

A component must never modify its own props, whether it is declared with a function or through a class.

function sum(a, b) {
  return a + b;
}
这样的函数被称为“纯函数”,因为该函数【不会尝试更改入参】,且多次调用下相同的入参始终返回相同的结果。
相反,下面这个函数则不是纯函数,因为它更改了自己的入参:
function withdraw(account, amount) { //account中的total属性被更改了
  account.total -= amount;
}

All React components must protect their props from being changed like pure functions.

Without violating the above rules, state allows React components to dynamically change the output content in response to user actions, network responses, or other changes.

The writing of the arrow function can solve the pointing of this

import React from "react"
class Test extends React.Component { 

  change(){
    console.log(this)  //输出的this是组件的实例属性
  }

  render () {
    return (
      <div>
         {/*如果不通过constructor做修正,那么我们可以直接在事件绑定的位置通过箭头函数的写法 --> 这种写法是直接沿用父函数(render)中的this  这个函数的父函数是render,这也说明了render中的this指向的就是【当前组件】的实例对象(react内部进行了修正)  */}
        <button onClick={()=>this.change()}>click</button>
      </div>
    )
  }
}

function App () {
  return (
    <div className="App">
      {/* 渲染定义的类组件 */}
      <Test></Test>
    </div>
  )
}
export default App

Suggestion: When defining a functional component during development, just define it directly with handle = () => {}, and then use it directly through this.handle when referencing.

destructuring assignment

Reference source: Destructuring assignment - JavaScript | MDN (mozilla.org)

Destructuring assignment: The value in the array or the property of the object can be taken out and assigned to our newly declared variable .

  • var defines a variable without the concept of a block. It can be accessed across blocks, but not across functions. If it is not initialized, undefined will appear, and no error will be reported.

  • Let defines variables, which can only be accessed in the block scope , and cannot be accessed across functions, and have no effect on the outside of the function.

  • const defines a constant, which can only be accessed in the block scope , and cannot be accessed across functions. It must be initialized (that is, must be assigned) when used, and cannot be modified .

Let's look at the basic use case first:

// 数组的解构 会按照变量的顺序进行解构
const x = [1, 2, 3, 4, 5];
const [y, z] = x;
console.log(y); // 1
console.log(z); // 2

const foo = ['one', 'two', 'three'];
const [red, yellow, green] = foo;
console.log(red); // "one"
console.log(yellow); // "two"
console.log(green); // "three"


//解构对象中的属性  对象中的
const obj = { a: 1, b: 2 };
const { a, b } = obj;
// 相当于下面的赋值写法
// const a = obj.a;
// const b = obj.b;

const obj2 = {  x:"你好", c: 2 };
const { x, c } = obj2;
console.log(x) //你好
console.log(c) //2

//报错
const obj3 = {  "你好", d: 2 };
const { x, c } = obj3;
console.log(x) 
console.log(d) 

const obj4 = {  x:"你好", e: 2 };
const { ddddd, e } = obj4;
console.log(ddddd) // undefined
console.log(e) //2

//如果想把属性赋值给新的变量名 那么应该怎么操作?
const obj4 = {  x:"你好", e: 2 };
const { x:ddddd, e } = obj4;
console.log(ddddd) // 你好
console.log(e) //2

Combining object and array destructuring assignment : case: want the third element in propsthe array , and only need namethe attribute in the object

const props = [
  { id: 1, name: 'a'},
  { id: 2, name: 'b'},
  { id: 3, name: 'c'}
];

const [,, { name }] = props;

console.log(name); // "c"

Default value : Each destructured attribute can have a default value . When the attribute does not exist or has a value undefinedof , the default value will be used . If the value of the attribute is null, it is not used.

const [a = 1] = []; // a 是 1
const { b = 2 } = { b: undefined }; // b 是 2
const { c = 2 } = { c: null }; // c 是 null

Rest property : You can use the rest property ( ...rest) to end the destructuring mode. This mode will store all remaining properties of the object or array into a new object or array. (used quite a lot)

const { a, ...others } = { a: 1, b: 2, c: 3 };
console.log(others); // { b: 2, c: 3 }

const [first, ...others2] = [1, 2, 3];
console.log(others2); // [2, 3]

useState

Case presentation:

// userState()就是我们使用的函数,我们可以在()中传一个初始值,这个初始值会被赋值给你声明的变量count,如果你想在其他地方修改这个count,那么可以调用声明的setCount()方法  并且把新的count值传到这个()中  setCount(newCount)
const [count, setCount] = useState(0); // 参数:状态初始值比如,传入 0 表示该状态的初始值为 0,返回值:数组,包含两个值:第一个是表示:状态值(state) 第二个是表示:修改该状态的函数(setState)


import { useState } from 'react'
function App() {
  // 参数:状态初始值比如,传入 0 表示该状态的初始值为 0
  // 返回值:数组,包含两个值:1 状态值(state) 2 修改该状态的函数(setState)
  const [count, setCount] = useState(0)
  return (
    <button onClick={() => { setCount(count + 1) }}>{count}</button>
  )
}
export default App

Status reading and modification:

  • Read status: The status provided by this method is a local variable inside the function, which can be used anywhere in the function

  • Modify status

    • setCount is a function, the parameter indicates最新的状态值

    • After calling the function, the old value will be replaced with the new value

    • After the state is modified, the view will change due to the state change

      Notice:

      • When modifying the state, be sure to replace the old state with the new state, and cannot directly modify the old state, especially the reference type

      • The initial value (parameter) of useState will only take effect when the component renders for the first time . That is to say, for each rendering in the future, useState gets the latest state value, and the React component will remember the latest state value each time

import { useState } from 'react'

function App() {
  const [count, setCount] = useState(0)
  // 在这里可以进行打印测试
  console.log(count)
  return (
    <button onClick={() => { setCount(count + 1) }}>{count}</button>
  )
}
export default App

useStatePrecautions :

  • Can only appear in function components or other hook functions

  • Cannot be nested in if/for/other functions (react recognizes each hook according to the calling order of hooks)

let num = 1
function List(){
  num++
  if(num / 2 === 0){
     const [name, setName] = useState('cp') 
  }
  const [list,setList] = useState([])
}
// 俩个hook的顺序不是固定的,这是不可以的!!!

useEffect

What is a side effect: In addition to the main function of a function, other functions are side effects. For React components, the main function is to render the UI according to the data (state/props) , other than that are all side effects

common side effects

  1. Data request ajax send

  2. Modify dom manually

  3. localstorage operation

Steps for usage

  1. import useEffectfunction

  2. Call useEffectthe function and pass in the callback function

  3. Write side effect processing (dom operation) in the callback function

  4. Modify the data state (used together with the set method in useState)

  5. Check for side effects

import { useEffect, useState } from 'react'

function App() {
  const [count, setCount] = useState(0)
 
  // useEffect() 调用副作用函数  ()=>{} 回调函数
  useEffect(()=>{
    // dom操作  进行操作
    document.title = `当前已点击了${count}次`
  })
  return (
    <button onClick={() => { setCount(count + 1) }}>{count}</button>
  )
}

export default App

Guess you like

Origin blog.csdn.net/weixin_53142722/article/details/128342226