日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

React組件通信淺析_React

作者:落雪小軒韓 ? 更新時間: 2023-01-31 編程語言

1、函數式組件

<script type="text/babel">
  // 1. 創建函數式組件
  function Demo() {
   // 里面的this是undefined,因為babel編譯后開啟了嚴格模式
    return <h2>我是用函數定義的組件(適用于【簡單組件】的定義)</h2>
  }
  // 2. 渲染組件到頁面
  ReactDOM.render(<Demo/>,document.getElementById('test'))
</script>

執行了ReactDOM.render(<Demo/>,document.getElementById('test'))之后,React解析組件標簽,找到了Demo組件,發現組件是用函數定義的,隨后調用該函數,將返回的虛擬DOM轉為真實DOM呈現在頁面中

注意:①函數名首字母必須大寫;②函數要有返回值;③render里面要寫組件標簽

2、類式組件

(1)類的基本知識

<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>

1.類中的構造器不是必須要寫的,要對實例進行一些初始化的操作,如添加指定屬性時才寫。

2.如果A類繼承了B類,且A類中寫了構造器,那么A類構造器中的super是必須要調用的。

3.類中所定義的方法,都放在了類的原型對象上,供實例去使用。

(1)類式組件

<script type="text/babel">
	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'))
</script>

執行了ReactDOM.render(<MyComponent/>,document.getElementById('test'))之后,React解析組件標簽,找到了MyComponent組件。發現組件是使用類定義的,隨后new出來該類的實例,并通過該實例調用到原型上的render方法。將render返回的虛擬DOM轉為真實DOM,隨后呈現在頁面中。

原文鏈接:https://blog.csdn.net/m0_46613429/article/details/128315968

欄目分類
最近更新