1、創建組件的方法
1.1、函數式無狀態組件
1.1.1、語法
1 function myComponent(props) { 2 return 3 <div>Hello {props.name}</div> 4 }
1.1.2、特點
● 它是為了創建純展示組件,這種組件只負責根據傳入的props
來展示,不涉及到state
狀態的操作。
● 組件不能訪問this對象
● 不能訪問生命周期方法
1.1.3、建議
如果可能,盡量使用無狀態組件
2、(組件的)狀態(state)和屬性(props)之間有何不同
2.1、State 是一種數據結構,用於組件掛載時所需數據的默認值。State 可能會隨着時間的推移而發生突變,但多數時候是作為用戶事件行為的結果。
2.2、Props(properties 的簡寫)則是組件的配置。props 由父組件傳遞給子組件,並且就子組件而言,props 是不可變的(immutable)。組件不能改變自身 的 props,但是可以把其子組件的 props 放在一起(統一管理)。Props 也不僅僅是數據–回調函數也可以通過 props 傳遞。
3、父子組件傳值
3.1、父組件Father.js
1 import React from 'react'; 2 import Son from './Son' 3 //父組件 4 class Father extends React.Component{ 5 constructor(){super(); 6 this.state={ 7 message:'' 8 } 9 } 10 //聲明一個函數,用戶接收子組件的傳值 11 getSonMess(msg){ 12 consloe.log('子組件傳過來的值 '+msg) 13 } 14 render(){ 15 return( 16 <React.Fragment> 17 <Son mess='hello Son' sonMess={this.getSonMess}> 18 </React.Fragment> 19 ); 20 } 21 } 22 export default Father;
3.2、子組件Son.js
1 import React from 'react'; 2 3 //子組件 4 class Son extends React.Component{ 5 6 render(){ 7 return ( 8 <React.Fragment> 9 10 {this.props.mess},{this.props.sonMess(123)} 11 12 </React.Fragment> 13 ); 14 } 15 16 } 17 18 export default Son;
4、兄弟組件傳值
4.1、組件Father.js
1 import React from 'react'; 2 import Son from './Son'; 3 import Son2 from './Son2'; 4 //父組件 5 class Father extends React.Component{ 6 7 constructor(){ 8 super(); 9 this.state = { 10 message:'' 11 } 12 } 13 14 //用於接收Son.js組件的數據函數 15 sonDatas(msg){ 16 this.setState({ 17 message:msg 18 }); 19 console.log("在Father.js中展示Son.js生成的數據:"+msg); 20 } 21 22 render(){ 23 return ( 24 <React.Fragment> 25 26 <h1>在Father組件中顯示:</h1> 27 <Son sondata={this.sonDatas.bind(this)}></Son> 28 <Son2 mess={this.state.message}></Son2> 29 </React.Fragment> 30 ); 31 } 32 33 } 34 35 export default Father;
4.2、第一個“兄弟”, 組件 Son.js
1 import React from 'react'; 2 3 //子組件 4 class Son extends React.Component{ 5 6 //按鈕點擊事件函數 7 sonClick(){ 8 this.props.sondata('這是從Son.js中生成的數據。。。'); 9 } 10 11 render(){ 12 return ( 13 <React.Fragment> 14 15 <button onClick={this.sonClick.bind(this)}>Son組件中的按鈕獲取數據</button> 16 17 </React.Fragment> 18 ); 19 } 20 21 } 22 23 export default Son;
4.3、第二個“兄弟”,組件Son2.js
1 import React from 'react'; 2 3 //子組件 4 class Son2 extends React.Component{ 5 6 render(){ 7 return ( 8 <React.Fragment> 9 10 <h1> 11 在Son2.js中展示Son.js中生成的數據,這個是Father.js傳過來的,數據是: 12 {this.props.mess} 13 </h1> 14 15 </React.Fragment> 16 ); 17 } 18 19 } 20 21 export default Son2;