010 复习class

  1. 类中的构造器不是必须写的,要对实例化进行初始化操作,如添加指定属性时才行
  2. 如果A继承B,则A构造器中的super()必须调用
  3. 类中的方法都是放在类的原型对象上,供实例使用
class Person {
  constructor(name) {
    this.name = name
  }

  //方法是放在了类的原型对象上,供实例使用
  //通过person实例调用方法,方法中的this指向实例对象
  speak() {
    console.log(this.name);
  }
}

//实现继承
class Student extends Person {
  constructor(name, grade) {
    // 继承name,改变指针
    super(name)
    this.grade = grade
  }
  //重写从父类原型对象继承过来的方法
  speak() {
    console.log(this.name, this.grade);
  }
}

const s1 = new Student('yy', 1)

011 类式组件

<div id="test"></div>
  <script type="text/babel">
    // 1.创建类式组件  继承自React.Component
    class MyComponent extends React.Component{
      render(){
        // render 放在那里的? --类的原型对象上,供实例使用
        // render中的this是谁 -- MyComponent组件实例对象
        return <h2>我是类定义的组件(复杂组件)</h2>
      }
    }

    ReactDOM.render(<MyComponent/>,document.getElementById('test'))
    // 1. react解析组件标签,找到了MyComponent组件
    // 2. 发现组件是类定义的,随后new出来该类的实例,并通过该实例调用到原型上的render方法
    // 3. 将render返回的虚拟DOM渲染到真实DOM

1 react解析组件标签,找到了MyComponent组件 2. 发现组件是类定义的,随后new出来该类的实例,并通过该实例调用到原型上的render方法 3. 将render返回的虚拟DOM渲染到真实DOM

012-013 对state的理解

简单组件没有state,复杂组件有

// 1. 创建组件
    class Weather extends React.Component{
      constructor(props){
        super(props)
        // react要求我们使用 对象表示state
          this.state = {
            isHot:false,
          }
      }
      render(){
        // 第一种写法
        // return <h2>今天好{this.state.isHot?'炎热':'凉爽'}</h2>

        // 第二种写法: 解构出来
        const {isHot} = this.state
        return <h2>今天好{isHot?'炎热':'凉爽'}</h2>
      }
    }
    ReactDOM.render(<Weather/>,document.getElementById('test'))
posted on 2022-04-14 14:32  Nemo头发挺多  阅读(19)  评论(0)    收藏  举报