高階函數: 接收函數做爲輸入,或者輸出另外一個函數的一類函數; 高階組件: 接收React組件做爲輸入,輸出一個新的React組件的組件。
高階組件經過包裹一個新傳入的React組件,通過一些邏輯處理,最終返回一個enchanted的React組件,是其餘組件調用.javascript
function getDisplayName(component) { return component.displayName || component.name || 'Component'; } export default function WithHOC(WrapComponent) { // 此處未定義名稱 return class extends React.Component { // 定義displayName; static displayName = `withHOC(${getDisplayName(WrapComponent)})`; render() { console.log('inside HOC'); return ( return <WrapComponent {...this.props} /> ) } } } App = WithHOC(App);
若是未定義displayName,那麼進行調試的時候,就會顯示以下:html
// react自動定義名稱 |---_class2 |---App ...
定義displayName後,顯示以下:java
|---withHOC(App) |---App ...
深刻理解javascript函數進階系列第二篇——函數柯里化
koa框架實踐與中間件原理解析
react事件傳參
只傳遞函數的一部分參數來調用它,讓它返回一個函數去處理剩下的參數react
在react裏,經過函數柯里化,咱們能夠經過傳入不一樣的參數來獲得不一樣的高階組件git
屬性代理最多見的高階組件的使用方式,上述描述的高階組件就是這種方式。它經過作一些操做,將被包裹組件的props和新生成的props一塊兒傳遞給此組件,這稱之爲屬性代理。github
import React from 'react'; export default function withHeader(WrapperComponent) { return class extends React.Component { render() { const newProps = { test: 'hoc' }; // 透傳props,而且傳遞新的newProps return ( <div> <WrapperComponent {...this.props} {...newProps} /> </div> ) } } }
這種方式返回的React組件繼承了被傳入的組件,因此它可以訪問到的區域、權限更多,相比屬性代理方式,它更像打入組織內部,對其進行修改。具體的能夠參考附錄裏提供的連接進行深刻學習。編程
export default function (WrappedComponent) { return class Inheritance extends WrappedComponent { componentDidMount() { // 能夠方便地獲得state,作一些更深刻的修改。 console.log(this.state); } render() { return super.render(); } } }
上述高階組件爲React組件加強了一個功能,若是須要同時增長多個功能須要怎麼作?這種場景很是常見,例如我既須要增長一個組件標題,又須要在此組件未加載完成時顯示Loading.app
@withHeader @withLoading class Demo extends Component{ }
使用compose能夠簡化上述過程,也能體現函數式編程的思想。框架
const enhance = compose(withHeader,withLoading); @enhance class Demo extends Component{ }
組合compose
compose能夠幫助咱們組合任意個(包括0個)高階函數,例如compose(a,b,c)回一個新的函數d,函數d依然接受一個函數做爲入參,只不過在內部會依次調用c,b,a,從表現層對使用者保持透明。
基於這個特性,咱們即可以很是便捷地爲某個組件加強或減弱其特徵,只須要去變動compose函數裏的參數個數即可。
compose函數實現方式有不少種,這裏推薦其中一個recompact.compose,詳情見下方參考類庫。
recompact:包含了一系列實用的高階組件庫
React Sortable:React拖動庫
深刻理解 React 高階組件:其中詳細介紹了屬性代理和反向繼承的區別。koa