React — Class类组件

一、Class类组件基础模板

import './App.css'; 
import {Component} from 'react'

class Counter extends Component{

  //编写组件的逻辑代码
  //1.状态变量 事件回调 UI
  //2.定义状态变量
  state = {
    count : 0
  }

  setCount = ()=>{
    this.setState({
      count : this.state.count +1
    })  
  }

  render(){
    const {count} = this.state
    return <>
    
        <div>
          <button>-</button>
          <span>
            {count}
          </span>
          <button onClick={this.setCount}>
            +
          </button>
        </div>
    </>
  }

}

function App() {
  return (
    <div className="App">
      <Counter></Counter>
    </div>
  );
}

export default App;

二、类组件生命周期函数

1.componentDidMount:组件挂载完毕自动执行 - 可以获取异步数据

2.componentWillUnmount :组件鞋子时自动执行 - 清理副作用

import "./App.css";
import { Component, useState } from "react";

class Counter extends Component {
  //编写组件的逻辑代码
  //1.状态变量 事件回调 UI
  //2.定义状态变量
  state = {
    count: 0,
  };

  setCount = () => {
    this.setState({
      count: this.state.count + 1,
    });
  };
  //生命周期函数
  //组件渲染完成自动执行 只会执行一次
  componentDidMount() {
    console.log("组件渲染完成");
  }
  //组件卸载的时候自动执行
  componentWillUnmount(){
    console.log("组件卸载完成");
  }

  render() {
    const { count } = this.state;

    return (
      <>
        <div>
          <button>-</button>
          <span>{count}</span>
          <button onClick={()=>this.setCount}>+</button>
        </div>
      </>
    );
  }
}

function App() {
  const [isShow,setShow] = useState(true)
  return (
    <div className="App">
      <button onClick={()=>setShow(!isShow)}>
        change
      </button>
      {isShow&&<Counter></Counter>}
    </div>
  );
}

export default App;

三、类组件的组件通信

1.父传子:通过prop绑定数据

class Son extends Component{
  render () {
    return <div>
      我是子组件
      <div>
        {/* 使用 this.props.属性 */}
        {this.props.msg}
      </div>
    </div>
  }
}

class Father extends Component{

  state = {
    msg : 'this is father msg'
  }
  render () {
    return <div>
      我是父组件
      {/* 直接通过子标签绑定身上的父组件的数据 */}
      <Son msg={this.state.msg}></Son>
    </div>
  }
}

2.子传父:通过prop绑定父组件中的函数,子组件调用

class Father extends Component{

  state = {
    msg : 'this is father msg',
    sonMsg : ''
  }
  getSonMsg=(sonMsg)=>{
    console.log(sonMsg)
      this.setState({
        sonMsg : sonMsg
      })
  }
  render () {
    return <div>
      我是父组件
      {/* 子传父:在子组件标签上绑定父组件的函数,子组件调用这个函数并传递参数 */}
      <Son msg={this.state.msg} onGetSonMsg={this.getSonMsg}></Son>
      <div>
        {this.state.sonMsg}
      </div>
    </div>
  }
}
class Son extends Component{

  state = {
    myMsg : 'this is Son msg'
  }
  render () {
    return <div>
      我是子组件>

      <div>

        <button onClick={()=>{
          this.props.onGetSonMsg(this.state.myMsg)
        }}>send Father</button>

      </div>
    </div>
  }
}

3.兄弟通信:状态提升,通过父组件做桥接

 

posted on 2024-03-15 21:54  萬事順意  阅读(147)  评论(0编辑  收藏  举报