react-18(状态-挂载)

import React, { Fragment } from "react";
import ReactDOM from "react-dom/client";

const root = ReactDOM.createRoot(document.getElementById("root"));

// 状态是组件自身设置/修改,由组件自身管理维护, 存储在this.state上
// 函数组件没有this,也没有状态, 又被称为无状态组件

// 挂载状态的方式:
// 1. 在constructor中初始化挂载状态
//    需要先调用super, super是父类的构造函数, 也就是React.Component, 组件的实例是需要父类来构建的
//    所以要么不写constructor, 要么写了constructor就要先调用super
//    并且组件的属性, 也是需要父类将props挂载组件的实例上super(props)
//    this.state = { count: 0 } 就可以挂载状态
//    状态必须是state

// 2. 直接为类添加state属性

class Example extends React.Component {
  // 1.
  // constructor (props) {
  //   super(props)
  //   this.state = {
  //     theme: 'light'
  //   }
  // }
  // 2. 
  state = {
    theme: 'light'
  }
  render () {
    const { theme } = this.state
    return (
      <div>
        <p>主题是: { theme }</p>
      </div>
    )
  }
}

class App extends React.Component {
  render () {
    return (
      <div>
        <Example count={1} />
      </div>
    )
  }
}

root.render(<App />)



// ES5和ES6继承的区别
// ES5 是先实例, 后继承
// ES6 是先继承, 后实例, 子类的实例要由父类构建

// function Person(name) {
//   this.name = name;
// }
// Person.prototype.sayName = function () {
//   console.log(this.name);
// }
// function Stutent(name) {
  
// }
// const tom = new Stutent()
// Person.call(tom, 'Tom')
// console.log(tom.name);

class Person {
  constructor(name) {
    this.name = name;
  }
  sayName () {
    console.log(this.name);
  }
}
// 父类会先创建一个空对象, 将属性和方法挂载在空对象上,然后把这个对象交给子类,作为子类的实例存在
class Student extends Person {
  constructor(name) {
    super(name)
  }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值