likes
comments
collection
share

React中使用类组件

作者站长头像
站长
· 阅读数 470

React中主要分为类组件和函数组件,在本文主要讲解为react中使用类组件:

我们先定义并导出一个叫Com的类组件

import React, { Component } from "react";
class Com extends Component {
    
}
export default Com;

接下来我们需要渲染一些Dom,并且定义一些状态数据,在react中响应式数据定义在state变量中

import React, { Component } from "react";
class Com extends Component {
  constructor(props) {
    super(props);
    this.state={
        time:5
    }
  }
  render() {
    return (
      <>
        <div>我是Com组件,现在是{this.state.time}点</div>
      </>
    );
  }
}
export default Com;

现在我们输出了一点div,并报出的现在的时间,每当我们修改state中的time属性是div中输出的时间就会随着改变

import React, { Component } from "react";
class Com extends Component {
  constructor(props) {
    super(props);
    this.state = {
      time: 5,
    };
  }
  componentDidMount() {
    this.setState({
      time: 6,
    });
  }
  render() {
    return (
      <>
        <div>我是Com组件,现在是{this.state.time}点</div>
      </>
    );
  }
}
export default Com;

我在生命周期函数中添加了一段setState来修改属性,现在渲染出的div中的时间也变成了6点

现在还有一个需求,就是每次点击渲染的div文字就需要让time加一,这就需要定义点击事件

import React, { Component } from "react";
class Com extends Component {
  constructor(props) {
    super(props);
    this.state = {
      time: 5,
    };
    this.newTime=this.newTime.bind(this);
  }
  componentDidMount() {
    this.setState({
      time: 6,
    });
  }
  newTime(){
      let oldTime=this.state.time
      this.setState({
          time:oldTime+1
      })
  }
  render() {
    return (
      <>
        <div onClick={this.newTime}>我是Com组件,现在是{this.state.time}点</div>
      </>
    );
  }
}
export default Com;

这样的话就可以绑定自定义事件了,在每次点击时获取当前时间后加一

!!:每次使用自定义事件时需要在构造器中使用bind函数进行绑定,将函数挂在到class实例上

简写方式:

import React, { Component } from "react";
class Com extends Component {
    state = {
      time: 5,
    };
  newTime=()=>{
      let oldTime=this.state.time
      this.setState({
          time:oldTime+1
      })
  }
  render() {
    return (
      <>
        <div onClick={this.newTime}>我是Com组件,现在是{this.state.time}点</div>
      </>
    );
  }
}
export default Com;

上面的类组件过于繁琐,增加了很多不必要的麻烦,因此我们可以在今后的开发中使用以上方式来简写

  1. state无需在写到构造器当中,直接写成实例属性
  2. 事件函数需要在构造器中使用bind绑定指向,直接使用箭头函数
  3. state和事件都不在依赖构造器构造器可以不用写