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)
}
}
react-18(状态-挂载)
最新推荐文章于 2024-05-23 17:56:57 发布