函數(shù)組件
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'))
執(zhí)行了ReactDOM.render(.......)之后,發(fā)生了什么?
1、react解析組件標(biāo)簽,找到了Person組件
2、發(fā)現(xiàn)組件是使用函數(shù)定義的,隨后調(diào)用該函數(shù),將返回的虛擬DOM轉(zhuǎn)為真實的DOM,隨后呈現(xiàn)在頁面中
類式組件
類的基本知識復(fù)習(xí)
創(chuàng)建一個Person類
Class Person{
//接收類的參數(shù),構(gòu)造器方法
constructor(name,age){
//構(gòu)造器中的this是誰?類的實例對象,誰new的類,this指向就是誰
this.name=name
this.age=age
}
//類的一般方法
speak(){
//speak方法放在了哪里?類的原型對象上,供實例使用
//通過Person實例調(diào)用speak時,speak中的this就是Person實例
console.log(`我叫${this.name},我年齡${this.age}`)
}
創(chuàng)建一個Person的實例對象
const P1=new Person('tom',18)
const P2=new Person('taotao',20)
P1()
P1.speak()//調(diào)用speak方法
類的繼承
//創(chuàng)建一個Student 類,繼承于Person類,此時Student中就有了Person中的方法
clss Student extends Person {
constructor(name,age,grade){
super(name,age)//繼承中,如果使用了constructor,必須使用super
this.grader=grade
}
}
//創(chuàng)建Student 實例
const s1=new Student ('小張',15,'高一')
s1()
類的總結(jié)
1、類中的構(gòu)造器(constructor)不是必須寫的,要對實例進行一些初始化的操作,如添加指定屬性時才寫
2、如果A類繼承了B類,且A類中寫了構(gòu)造器,那么A類構(gòu)造器中的super是必須要調(diào)用的
3、類中定義的方法,都是放在了類的原型對象中,供類的實例調(diào)用
創(chuàng)建類式組件
import React, { Component } from 'react'
//構(gòu)造器調(diào)用幾次?1次
export default class index extends Component {//必須繼承react中的Component 的類
/*
高階函數(shù):如果一個函數(shù)符合下邊2個規(guī)范中的任何一個,那么該函數(shù)就是高階函數(shù)
1,若A函數(shù),接收得參數(shù)是一個函數(shù),那么A就可以被稱之為高階函數(shù)
2,若A函數(shù),調(diào)用的返回值依然是一個函數(shù),那么A就是可以稱之為高階函數(shù)
*/
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)
}
}
}