React 组件的两种创建方式

函数组件

  function Person(props){
      const {name,age,sex}=props
      return(
        <ul>
          <li>姓名:{name}</li>
          <li>年龄:{age}</li>
          <li>性别:{sex}</li>
          </ul>
      )
    }

渲染

 const p={name:'老刘',age:18,sex:'女'}
 ReactDOM.render(<Person {...p} />,document.getElementById('test'))

执行了ReactDOM.render(.......)之后,发生了什么?
1、react解析组件标签,找到了Person组件
2、发现组件是使用函数定义的,随后调用该函数,将返回的虚拟DOM转为真实的DOM,随后呈现在页面中

类式组件

类的基本知识复习

创建一个Person类

Class Person{
  //接收类的参数,构造器方法
  constructor(name,age){
//构造器中的this是谁?类的实例对象,谁new的类,this指向就是谁
      this.name=name
      this.age=age
}
//类的一般方法
speak(){
//speak方法放在了哪里?类的原型对象上,供实例使用
//通过Person实例调用speak时,speak中的this就是Person实例
   console.log(`我叫${this.name},我年龄${this.age}`)
}

创建一个Person的实例对象

const P1=new Person('tom',18)
const P2=new Person('taotao',20)
P1()
P1.speak()//调用speak方法

类的继承

//创建一个Student 类,继承于Person类,此时Student中就有了Person中的方法
clss Student extends Person {
  constructor(name,age,grade){
        super(name,age)//继承中,如果使用了constructor,必须使用super
        this.grader=grade
  }
}
//创建Student 实例
const s1=new Student ('小张',15,'高一')
s1()

类的总结

1、类中的构造器(constructor)不是必须写的,要对实例进行一些初始化的操作,如添加指定属性时才写
2、如果A类继承了B类,且A类中写了构造器,那么A类构造器中的super是必须要调用的
3、类中定义的方法,都是放在了类的原型对象中,供类的实例调用

创建类式组件

import React, { Component } from 'react'
//构造器调用几次?1次
export default class index extends Component {//必须继承react中的Component 的类
 /*
        高阶函数:如果一个函数符合下边2个规范中的任何一个,那么该函数就是高阶函数
        1,若A函数,接收得参数是一个函数,那么A就可以被称之为高阶函数
        2,若A函数,调用的返回值依然是一个函数,那么A就是可以称之为高阶函数
        */
  state = {
    mouse: false
  }
  render() {
    const { item } = this.props;  //props只能读不能改
    return (
      <li onMouseLeave={this.handleMouse(false)} onMouseEnter={this.handleMouse(true)} style={{ backgroundColor: this.state.mouse ? '#ddd' : "white" }}>
        <label >
          <input type="checkbox" checked={item.done} onChange={this.handleCheck(item.id)} />
          <span>{item.name}</span>
        </label>
        <button style={{ display: this.state.mouse ? 'block' : "none" }} onClick={this.deletFunction(item.id)}>删除</button>
      </li>
    )
  }
  handleMouse = (flag) => {
    return () => {
      this.setState({
        mouse: flag
      })
    }
  }
  deletFunction = (id) => {
    return () => {
      this.props.deletFunct(id)
    }
  }
  handleCheck = (id) => {
    return (event) => {
      this.props.changeTodo(id, event.target.checked)
    }
  }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容