React & 日常用法与基本原则(不定时更新)

一、React 日常用法

1. 类名的定义

<div className="box"></div> 

2. 类组件

import React from 'react';
class MyButton extends React.Component {
    
    
  render() {
    
    
    return (
      <button>{
    
     this.props.text }</button>
    )
  }
}
<div className="box">
  <MyButton text='提交' />
</div>

3. 函数组件

import React from 'react';
const MyButton = (props) => {
    
    
  return (
    <button>{
    
    props.text}</button>
  );
}
<div className="box">
  <MyButton text='提交' />
</div>

4. 组件添加事件

这里以点击事件为例,其它格式均以 onXXX 驼峰形式。

const clickButton = () => {
    
    
  console.log('You just clicked me.')
}
<button onClick={
    
    clickButton}>
  点我
</button>

5. 类组件定义 state

import React from 'react';
class User extends React.Component {
    
    
  /**
   * 1. state 必须在 constructor 初始化
   * 2. 使用 constructor 必须调用 super(props)
   * 3. 事件调用 this.setState 更新数据时该事件必须在 constructor 先 .bind(this)
   */
  constructor(props) {
    
    
    super(props)
    this.state = {
    
    
      name: 'Tony',
      age: 20
    }

    this.changeUser = this.changeUser.bind(this)
  }

  changeUser() {
    
    
    this.setState({
    
    
      name: 'Jack',
      age: 18
    });
  }

  renderButton() {
    
    
    return (
      <button onClick={
    
    this.changeUser}>更换姓名</button>
    )
  }

  render() {
    
    
    return (
      <div className='user'>
        <span>Name: {
    
     this.state.name }</span>
        <br />
        <span>Age: {
    
     this.state.age }</span>
        <div>
          {
    
     this.renderButton() }
        </div>
      </div>
    );
  }
}

6. 函数组件定义 state

import React from 'react';
import {
    
     useState, useEffect } from 'react';
class MyButton extends React.Component {
    
    
  const [userName, setUserName] = useState('小明');
  setUserName(state, newUserName) {
    
     // 变更姓名,这里暂时没地方调用,仅提供案例。
    return {
    
    
    	...state,
    	newUserName,
    }
  }
  render() {
    
    
    return (
      <div>{
    
     userName }</div>
      <button>{
    
     this.props.text }</button>
    )
  }
}
<div className="box">
  <MyButton text='提交' />
</div>

7. 类子组件通过 props 来调用父组件的函数

import React from 'react';
class Father extends React.Component {
    
    
  constructor(props) {
    
    
    super(props)
    this.getFatherName = this.getFatherName.bind(this)
  }
  getFatherName() {
    
    
    return 'Jack'
  }
  render() {
    
    
    return (
      <div className="Father">
      	// 引入类子组件
        <Child getFatherName={
    
    this.getFatherName}/>
      </div>
    )
  }
}
// 类子组件
class Child extends React.Component {
    
    
  constructor(props) {
    
    
    super(props)
    this.emitFatherFun = this.emitFatherFun.bind(this)
  }
  emitFatherFun() {
    
    
    alert(this.props.getFatherName())
  }
  render() {
    
    
    return (
      <div className="Child">
        <button onClick={
    
    this.emitFatherFun}>点击触发父组件函数</button>
      </div>
    )
  }
}

8. 类组件引入函数组件

import React from 'react';
/**
 * 1. props 直接使用,不用加上 this
 * 2. 定义函数组件只需 return 元素即可,不用像类那样要通过 extends React.Component 来定义组件。
 */
const PureGreetCom = (props) => {
    
    
  return (
    <div className="PureCom">
      <span>Hi, {
    
     props.name } </span>
    </div>
  )
}

class Father extends React.Component {
    
    
  render() {
    
    
    return (
      // 引入函数组件
      <PureGreetCom name="Jack" />
    )
  }
}

9. 类组件的生命周期函数


class CMP extends React.Component {
    
    
  constructor() {
    
    }
  componentDidMount() {
    
    } // 组件第一次加载时执行
  componentDidUpdate() {
    
    } // 组件更新时执行
  componentWillUnmount() {
    
    } // 组件即将销毁时执行
}

10. 使用 map 数组渲染多个组件或元素


const UL = () => {
    
    
  return (
    <ul>
      {
    
     List }
    </ul>
  )
}
/**
 * 循环遍历元素时与 Vue 一样,要加上唯一 key
 */
const List = [1, 2, 3, 4, 5].map((index) => {
    
    
  return (
    <li key={
    
    index}> {
    
     index } </li>
  )
})

// 使用方式
<UL />

11. 定义变量组件


/**
 * 1. 与函数/类组件不同,变量组件的使用方式要用 { Hello } 而不是 <Hello />
 */
const name = 'Jack'
const Hello = <h1> Hello {
    
     name }</h1>

12. 组合 props.children (在 Vue 中称为‘插槽’)

/**
 * 普通插槽
 */
const List = () => {
    
    
  return (
    <div>
      {
    
     props.children }
    </div>
  )
}
/**
 * 具名插槽
 */
import React from 'react';
const Bar = () => {
    
    
  return (
    <div className="left">{
    
     props.left }</div>
    <div className="right">{
    
     props.right } </div>
  )
}

class Main extends React.Component {
    
    
  render() {
    
    
    return (
      <List>
        {
    
    [1, 2, 3].map((i) => {
    
    
          return <li> {
    
     i } </li>
        })}
      </List>
      <Bar>
        left={
    
    // 指向 Bar 里的 left 插槽。 
          <div className="BarLeft"></div>
        }
        right={
    
     // 指向 Bar 里的 right 插槽。 
          <div className="BarRight"></div>
        }
      </Bar>
    )
  }
}

13. 函数组件使用 useEffect/useState 钩子

useEffect 可以模拟类组件中的三大生命周期函数,useState 可以用来声明响应式变量。

import {
    
     useState, useEffect } from 'react';
const List = () => {
    
    
  const [arr, setArr] = useState([1, 2, 3, 4])
  useEffect(() => {
    
    
	// 第一次加载时模拟 componentDidMount。
	// Do something ...
    return () => {
    
    
      // 组件销毁时模拟 componentWillUnmount。
      // Do something ...
    };
  }, [arr]) // 字段更新时模拟 omponentDidUpdate。
  return (
    <ul>
      {
    
    arr.map((num) => Item(num, setArr) )}
    </ul>
  )
}

二、React 编写原则

  1. state 不可直接修改,要用副本代替合并,遵循不可变原则。
  2. 子组件不可直接修改 props ,此操作由父组件负责,遵循自顶向下原则。
  3. setState({}) 是异步更新、setState(() => {}) 是同步更新。

猜你喜欢

转载自blog.csdn.net/cookcyq__/article/details/129331516
今日推荐