
高階組件的定義
接受React組件作為輸入,輸出一個新的React組件。
概念源自于高階函數,將函數作為參數,或者輸出一個函數,如map,reduce,sort。
用haskell的函數簽名來表示:
hocFactory:: W: React.component => E: React.component
使用場景
可以用來對組件進行二次加工和抽象,比如:對Input組件進行樣式改動、添加新的props屬性;某些可以復用的邏輯抽象后再注入組件。
所以 HOC 的作用大概有以下幾點:
- 代碼復用和邏輯抽象
- 對 state 和 props 進行抽象和操作
- Render 劫持
如何實現
- 屬性代理(props proxy):高階組件通過被包裹的React組件來操作props,從而能夠實現控制props、引用refs、抽象state。
1.1 控制props
import React, { Component, Fragment } from 'react';const MyContainer = WrappedComponent =>class extends Component {render() {const newProps = {text: 'newText',};return (<><span>通過 props proxy 封裝HOC</span><WrappedComponent {...this.props} {...newProps} /></>);}};
從這里可以看到,在render中返回來傳入WrappedComponent 的React組件,這樣我們就可以通過HOC在props中傳遞屬性、添加組件及樣式等等。
使用也是非常簡單:
import React, { Component } from 'react';
import MyContainer from './MyContainer.jsx';class App extends Component {...
}export default MyContainer(App);
當然也可以使用裝飾器@decorator:”接收一個類作為參數,返回一個新的內部類“,與HOC的定義如出一轍,十分契合。
import React, { Component } from 'react';
import MyContainer from './MyContainer.jsx';@MyContainer
class App extends Component {...
}export default App;
1.2 通過refs使用引用
import React, { Component } from 'react';const RefsHOC = WrappedComponent =>class extends Component {proc(wrappedComponentInstance) {wrappedComponentInstance.refresh();}render() {const props = Object.assign({}, this.props, { ref: this.proc.bind(this) });return <WrappedComponent {...props} />;}};export default RefsHOC;
render() 時會執行 ref 回調,即proc方法,該方法可以獲取 WrappedComponent 的實例,其中包含組件的 props,方法,context等。我們也可以在 proc 中進行一些操作,如控制組件刷新等。
1.3 抽象state
我們可以通過向 WarppedComponent 提供 props 和 回調函數抽象state,將原組件抽象成展示型組件,隔離內部state。
import React, { Component } from 'react';const MyContainer = WrappedComponent =>class extends Component {constructor(props) {super(props);this.state = {name: '',};}onHandleChange = e => {const val = e.target.value;this.setState({name: val,});};render() {const newProps = {name: {value: this.state.name,onChange: this.onHandleChange,},};return <WrappedComponent {...this.props} {...newProps} />;}};
我們將 input 組件中 name props 的 onChange方法提取到了高階組件中,這樣就有效的抽象了同樣的state操作。
import React, { Component } from 'react';
import MyContainer from './MyContainer.jsx';@MyContainer
class MyInput extends Component {render() {return <input type="text" {...this.props.name} />;}
}export default MyInput;
參考鏈接
深入React技術棧?book.douban.comJavascript 中的裝飾器?aotu.io