項目創(chuàng)建
npx craete-react-app my-app
cd my-app
npm start
面向組件編程
組件:用來實現(xiàn)局部功能效果的代碼和資源的集合
1.函數(shù)式組件:
function MyComponent(){
return <h2>我是用函數(shù)定義的組件(適用于簡單組件的定義)</h2>
}
ReactDOM.render( <MyComponent/>,document.getElementById('test') )
類的基本知識:
//創(chuàng)建一個Person類
Class Person {
//構(gòu)造器方法
constructor(name,age){
//構(gòu)造器中的this是誰?—類的實例對象
this.name = name
this.age = age
}
//一般方法
speak(){
//speak方法放在哪里?—Person的原型對象上扶踊,供實例使用
//通過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('jerry',19)
p1.speak()
p2.speak()
//創(chuàng)建一個Student類,繼承Person類
class Student extends Person {
//constructor構(gòu)造器不是一個必須要寫的東西
constructor(name,age,grade){
super(name,age) //must need
this.grade = grade
}
//重寫從父類繼承過來的方法
speak(){
console.log(`我叫${this.name},年齡${this.age}秘豹,我讀的是${this.grade}年級`);
}
study(){
//study方法放在哪里?—Student類的原型對象上芝此,供實例使用
//通過Student實例調(diào)用study時憋肖,study中的this就是Student實例
console.log("我很努力的學(xué)習(xí)");
}
}
const s1 = new Student("小張",15)
console.log(s1);
s1.speak();
s1.study();
/*
1.類中的構(gòu)造器不是必須寫的,要對實例進(jìn)行一些初始化的操作婚苹,如添加指定屬性時才寫;
2.如果A類繼承了B類岸更,且A類中寫了構(gòu)造器,那么A類構(gòu)造器中super是必須要調(diào)用的;
3.類中定義的方法膊升,都是放在了類的原型對象上怎炊,供實例去使用
*/
2.類式組件:
//1.創(chuàng)建類式組件
class Mycomponent extends React.Component{
render(){
//render是放在哪里的?—Mycomponent 類的原型對象上廓译,供實例使用评肆。
//render中的this是誰?—Mycomponent實例對象 <=> Mycomponent組件實例對象非区。
return <h2>我是用類定義的組件,適用于復(fù)雜組件</h2>
}
}
//2.渲染組件到頁面
ReactDOM.render(<MyComponent />,document.getElementById('test') )
/*
執(zhí)行了ReactDOM.render(<MyComponent/>...之后發(fā)生了什么瓜挽?
1.React解析組件標(biāo)簽,找到了MyComponent組件征绸。
2.發(fā)現(xiàn)組件時使用類定義的久橙,React隨后new出來該類的實例,并通過該實例調(diào)用到了原型上的render()方法管怠。
3.將render返回的虛擬DOM轉(zhuǎn)為真實DOM并呈現(xiàn)在頁面當(dāng)中淆衷。
*/
生命周期
1.初始化階段:由ReactDOM.render()觸發(fā)—初次渲染
(1). constructor
(2). getDerivedStateFromProps //從Props得到一個派生的狀態(tài),即state的值任何時候都取決與props渤弛,派生狀態(tài)會導(dǎo)致代碼冗余組件難以維護(hù)祝拯,罕見
(3). render()
(4). componentDidMount() //組件掛載完了
2.更新階段:由組件內(nèi)部this.setState()或父組件重新>render觸發(fā)
(1). getDerivedStateFromProps
(2). shouldComponentUpdate()
(3). render()
(4. getSnapshotBeforeUpdate //得到快照
(5). componentDidUpdate()
3.卸載組件:由ReactDOM.unmountComponentAtNode()觸發(fā)
(1). componentWillUnmount()