React-cnblog

1. 生命周期

  • 老版本16.3及以前

  • 新版本16.4 及以后

1.2 错误处理的生命周期

  • static getDerivedStateFormError
  • componentDidCatch

2. 父子通讯

  • 父传子
    • props
    • Prototype Methods
      • 即把子组件写成一个非受控组件,父组件定义ref,绑定给子组件
      • this.ref.current.方法名(参数) 父组件的数据就通过参数传递
  • 子传父
    • 给子组件提供事件,子组件需要传递时调用
    • 事件冒泡
      • 子组件发生某些事件需要改变父组件某些数据时
      • 事件通过冒泡传递给父组件,父组件通过事件处理函数处理

3. setState函数的执行是同步的还是异步的

  • 两种情况
    • 同步
      • 原生事件
      • setTimeOut
    • 异步
      • React的合成事件(绑定的事件)
      • 钩子函数,当当就是钩子函数,不包裹上述同步的情况
import React, { Component } from 'react'

export default class SetStateComponent extends Component {
  state= {
    count : 0
  }
  // 同步:原生事件和setTimeout 
  // componentDidMount() {
  //   setTimeout(()=>{
  //     this.setState({count: this.state.count+1});
  //     console.log(`this.state.count`, this.state.count);
  //   })
  //   const ele = document.getElementById('element');
  //   ele.onclick = ()=>{
  //     this.setState({count: this.state.count+1});
  //     console.log(`this.state.count`, this.state.count)
  //   }
  // }
  componentDidMount() {
    this.setState({count: this.state.count+1});
    console.log(`this.state.count`, this.state.count)
  }
  
  // 异步: react合成事件 生命周期钩子函数
  handleClick = ()=> { 
    this.setState({count: this.state.count+1});
    console.log(`this.state.count`, this.state.count)
  }
  render() {
    return (
      <div>
        <button id="element">add</button>
        <button onClick={this.handleClick}>add</button>
      </div>
    )
  }
}

4. renderProps

  • render prop 是指一种在React组件之间使用值为prop的函数共享代码的技术

  • 场景,一个组件中的state里面的值被多个其他组件使用(跨任意层级的)

  • 有点像redux的原理

import React, { Component } from 'react'

class Cat extends Component {
  render(){
    const mouse = this.props.mouse
    return (
      <img src="/favicon.ico" style={{position:"absolute",left:mouse.x,top: mouse.y}}/>
    )
  }
}

class Mouse extends Component {
  state= {
    x:0,
    y:0,
  }
  // 获取鼠标的x轴和y轴的信息
  handleMouseMove = (event)=>{
    const x = event.clientX;
    const y = event.clientY;
    //更新state 坐标值
    this.setState({
      x,
      y
    })
  }
  render(){
    return (
      <div style={{background:'red',height:'100vh'}} onMouseMove={this.handleMouseMove}>
        { this.props.render(this.state) }
      </div>
    )
  }
}

export default class MoseMove extends Component {
  render() {
    return (
      <div>
        <h1>鼠标移动</h1>
        <Mouse render={mouse=>(
          <Cat mouse={mouse}/>
        )}/>
      </div>
    )
  }
}

5. React-router的路由模式

6.jsx

  • 一个语法糖,XML中可以写js语法
  • 通过babel/preset-react转换成React.createElement创建的虚拟dom
  • 虚拟dom再通过render函数转换成页面真实的dom
posted @ 2023-02-05 10:13  凌歆  阅读(20)  评论(0)    收藏  举报