一、基本理解和使用
1. 使用React開發者工具調試
2. 效果
函數式組件:
<script type="text/babel"> //1.創建函數式組件 function MyComponent(){ console.log(this); //此處的this是undefined,因爲babel編譯後開啓了嚴格模式 return <h2>我是用函數定義的組件(適用於【簡單組件】的定義)</h2> } //2.渲染組件到頁面 ReactDOM.render(<MyComponent/>,document.getElementById('test')) /* 執行了ReactDOM.render(<MyComponent/>.......之後,發生了什麼? 1.React解析組件標籤,找到了MyComponent組件。 2.發現組件是使用函數定義的,隨後調用該函數,將返回的虛擬DOM轉爲真實DOM,隨後呈現在頁面中。 */ </script>
類式組件:
<script type="text/babel"> //1.創建類式組件 class MyComponent extends React.Component { render(){ //render是放在哪裏的?—— MyComponent的原型對象上,供實例使用。 //render中的this是誰?—— MyComponent的實例對象 <=> MyComponent組件實例對象。 console.log('render中的this:',this); return <h2>我是用類定義的組件(適用於【複雜組件】的定義)</h2> } } //2.渲染組件到頁面 ReactDOM.render(<MyComponent/>,document.getElementById('test')) /* 執行了ReactDOM.render(<MyComponent/>.......之後,發生了什麼? 1.React解析組件標籤,找到了MyComponent組件。 2.發現組件是使用類定義的,隨後new出來該類的實例,並通過該實例調用到原型上的render方法。 3.將render返回的虛擬DOM轉爲真實DOM,隨後呈現在頁面中。 */ </script>
3. 注意
- 組件名必須首字母大寫
- 虛擬DOM元素只能有一個根元素
- 虛擬DOM元素必須有結束標籤
4. 渲染類組件標籤的基本流程
- React內部會創建組件實例對象
- 調用render()得到虛擬DOM, 並解析爲真實DOM
- 插入到指定的頁面元素內部
5. 類的相關知識
1.類中的構造器不是必須要寫的,要對實例進行一些初始化的操作,如添加指定屬性時才寫。 2.如果A類繼承了B類,且A類中寫了構造器,那麼A類構造器中的super是必須要調用的。 3.類中所定義的方法,都放在了類的原型對象上,供實例去使用。
<script type="text/javascript" > //創建一個Person類 class Person { //構造器方法 constructor(name,age){ //構造器中的this是誰?—— 類的實例對象 this.name = name this.age = age } //一般方法 speak(){ //speak方法放在了哪裏?——類的原型對象上,供實例使用 //通過Person實例調用speak時,speak中的this就是Person實例 console.log(`我叫${this.name},我年齡是${this.age}`); } } //創建一個Student類,繼承於Person類 class Student extends Person { constructor(name,age,grade){ super(name,age) this.grade = grade this.school = '尚硅谷' } //重寫從父類繼承過來的方法 speak(){ console.log(`我叫${this.name},我年齡是${this.age},我讀的是${this.grade}年級`); this.study() } study(){ //study方法放在了哪裏?——類的原型對象上,供實例使用 //通過Student實例調用study時,study中的this就是Student實例 console.log('我很努力的學習'); } } class Car { constructor(name,price){ this.name = name this.price = price // this.wheel = 4 } //類中可以直接寫賦值語句,如下代碼的含義是:給Car的實例對象添加一個屬性,名爲a,值爲1 a = 1 wheel = 4 static demo = 100 } const c1 = new Car('奔馳c63',199) console.log(c1); console.log(Car.demo); </script>