React.js高階函數的定義與使用

 1 /* 高階函數的簡單定義與使用
 2       一: 先定義一個普通組件
 3       二: 用function higherOrder(WrappendComponent) {
 4                 return 
 5             } 將組件包裹起來,並用export default higherOrder將這個高階函數拋出去
 6       三: 使用時先導入這個高階函數,直接將組件以參數的方式傳遞進來便可
 7 */
 8 import React,{Component} from 'react';
 9 
10 /** 
11  * 定義高階函數
12  */
13 function higherOrder(WrappendComponent) {
14     return class A extends Component {
15         render() {
16             return (
17                 // 這個 WrappendComponent 將被傳遞進來的組件代替
18                 <WrappendComponent />
19             );
20         }
21     }
22 }
23 export default higherOrder;
24 // ===================================== 分界符 ==============================================
25 /** 
26  * 使用高階函數
27  *   一: 先將高階函數引入
28  *   二: 將組件以參數的方式傳遞進去
29  */
30 import higherOrder from './';
31 class B extends Component {
32     render() {
33         return (
34             <div>
35                 子組件
36             </div>
37         );
38     }
39 }
40 // 調用高階函數:
41 export default higherOrder(B)

 高階組件應用:css

 1 import React,{ Component } from 'react';
 2 import './App.css';
 3 import B from './b';
 4 class App extends Component {
 5   render() {
 6     return (
 7       <div>
 8         <B name={'張三'} age={12}/>
 9       </div>
10     );
11   }
12 }
13 
14 export default App;
 1 import React,{Component} from 'react';
 2 import A from './a';
 3 /*
 4  *  普通顯示組件
 5  */
 6 class B extends Component {
 7     render() {
 8         return (
 9             <div>
10                 個人名字叫:{this.props.name}
11                 <br />
12                 個人年齡是:{this.props.age}
13                 <br />
14                 個人性別是:{this.props.sex}
15                 <br />
16             </div>
17         );
18     }
19 }
20 // 調用高階函數A:
21 export default A('提示')(B)
 1 import React,{Component} from 'react';
 2 
 3 /** 
 4  * 定義高階函數 A
 5  */
 6 export default (title) => WrappendComponent => class A extends Component {
 7 
 8     render() {
 9         // 經過取出 props 來控制要傳入子組件的 props
10         const {age, ...otherProps} = this.props
11         return (
12             <div>
13                 <div>{title}                 X</div>
14                 {/* // 這個 WrappendComponent 將被傳遞進來的組件代替 */}
15                 <div>
16                  // 在App.js中,咱們並無將sex這個屬性傳遞給B,而是經過A高階函數來傳遞
17                  <WrappendComponent sex={'男'} {...otherProps}/>
18                 </div>
19                 
20             </div>
21         );
22     }
23 }// 上述三個頁面執行流程:App.js渲染B.js定義的頁面內容。而B.js調用了高階函數A.js,因此實際留存爲:App.js傳遞的值先到A.js高階函數,A.js高階函數對值進行處理而後再傳遞給B.js顯示
相關文章
相關標籤/搜索