Vue.js中父子組件數據傳遞:Props Down , Events Up
Angular中父子組件數據傳遞:Props Down, Events Up
React中父子組件數據傳遞:Props Down,Props Up
一、React中父子組件數據傳遞
父 => 子:父親通過子組件的自定義屬性,把自己的數據傳遞下去
Parent.js:
<Child myNameInChild={this.state.myNameParent}/>
Child.js:
<h3>{this.props.myNameInChild}的照片牆</h3>
子 =>父: 父親通過子組件的自定義屬性,把自己的方法傳遞下去;子組件調用此方法,傳遞實參.
"Props Up"的原理:
Parent.js:
doModifyMyName = (newName)=>{ }
<Child modifyName={ this.doModifyMyName }/>
Child.js:
this.props.modifyName('ABC');
Parent p =new Parent()
p.doModifyMyName = function(newName){ ..... }
Child c =new Child()
c.modifyMyName = p.doModifyMyName //父的方法傳給子
c.modifyMyName('ABC');
React中沒有直接的兄弟間數據傳遞機制,只能借助父組件: 兄弟1 => 父組件 => 兄弟2
Parent.js
constructor(){
super()
this.c2 = React.createRef() //子組件的引用
}
---------------------------------------------------------------
<h3.MyC03 ref={this.c3}> //子組件的引用綁定到某個孩子
---------------------------------------------------------------------
this.c3.current 是孩子對象
Vue.js中父組件獲得子組件的引用:
<Child ref="c2"/>
this.$refs.c2
------------------------------------
<Child #c2/>
@ViewChild('c2',{static:true})
private child2
------------------------------------
React中父組件獲得子組件的引用
<Child ref={ }/>
二、理論知識補充: class中的靜態(static)成員
類(class) 中的成員分為兩大類:
①實例成員:實例屬性、實例方法
②靜態成員:靜態屬性、靜態方法
三、面試題:React中組件的生命周期鈎子函數 ------比較凌亂
提示: React不同版本中生命周期鈎子函數各不相同!React16.3和React16.4中的都不相同!
React組件的生命周期鈎子函數分為三組:
1)首次渲染相關函數
①contstructor()
②componentWillMount() (已廢棄)===getDeriveStateFormProps() 用於將this.props轉為this.state
③render()
④componentDidMount() 用於初始化組件中的數據,如異步獲取服務器端數據
2)二次渲染相關函數(props屬性更改、setState狀態修改)
①getDerivedStateFromProps() 需要返回轉換得到state對象或null
②shouldComponentUpdate() 需要返回true或false
③render()
④componentDidUpdate()
3)組件卸載相關函數
①componentWillUnmount() 用於銷毀組件創建的長期存在的數據,如定時器...
強化記憶:三大框架,組件加載完成和卸載完成鈎子函數
Vue.js Angular React
組件加載完成 mounted(){} ngOnInit(){ } componentDidMount(){}
組件即將卸載 beforeDestroy(){} ngOnDestory(){} componentWillUnmount(){}
四、復習:前端技術中創建移動App的技術有哪些?
①原生開發:Android下用Java/Kotlin,IOS下用OC/Swift
②H5/WebView:使用瀏覽器內核打開特定的頁面 ------------Vue.js/Mint-UI
③混編開發:H5/WebView+Cordova/PhoneGap -------------Angular/lonic
④JS Bridge:代碼使用JS,使用橋梁轉換,運行時是Java或OC ------------ React/RN
⑤Flutter:使用全新的Dart語言,直接在手機GPU上繪圖