React 高阶组件HOC详解
參考鏈接:
https://juejin.cn/post/6844903815762673671
https://juejin.cn/post/6844904050236850184
前言
高階組件與自定義hooks是React 目前流行的狀態邏輯復用的兩種解決方案
1.高階組件是什么
高階組件就是一個函數,且該函數接受一個組件作為參數,并返回一個新的組件。
高階組件(HOC)是React中的高級技術,用來重用組件邏輯。但高階組件本身并不是React API。它只是一種模式,這種模式是由React自身的組合性質必然產生的。
HOC簡單例子:
//HOC function visible(WrappedComponent) {return class extends Component {render() {const { visible, ...props } = this.props;if (visible === false) return null;return <WrappedComponent {...props} />;}} }// 用HOC包裹組件 class Example extends Component {render() {return <span>示例組件</span>;} } export default HOC(Example) //或者用decorator方式 @HOC class Example extends Component {render() {return <span>示例組件</span>;} } export default Example//使用 <Example visible={false}/>上面的代碼就是一個HOC的簡單應用,函數接收一個組件作為參數,并返回一個新組件,新組建可以接收一個visible props,根據visible的值來判斷是否渲染傳入的組件。
2 高階組件實現方式
2.1屬性代理
將一個React組件作為參數傳入函數中,函數返回一個自定義的組件。該自定義組件的render函數中返回傳入的React組件。
由此可以代理并操作傳入的React組件的props,并且決定如何渲染,實際上 ,這種方式生成的高階組件就是原組件的父組件,上面的函數visible就是一個HOC屬性代理的實現方式。
這種實現方式下,HOC容器組件和傳入組件的生命周期調用順序和父,子組件的生命周期順序是一致的。類似堆棧調用(先入后出)
function proxyHOC(WrappedComponent) {return class extends Component {render() {return <WrappedComponent {...this.props} />;}} } //使用示例 class Example extends Component {render() {return <input name="name" {...this.props.name} />;} } export default HOC(Example)通過屬性代理實現的HOC可具有以下功能:
(1)操作props
可以對傳入組件的props進行增加、修改、刪除或者根據特定的props進行特殊的操作。
注意,使用HOC包裹后的組件,在給組件傳入props時實際傳入到了HOC的container容器組件中,如不需要操作props,請務必在容器組件中將props再度傳給傳入組件,否則傳入組件不會接收到props
function proxyHOC(WrappedComponent) {return class Container extends Component {render() {const newProps = {...this.props,user: "ConardLi"}return <WrappedComponent {...newProps} />;}} }(2)獲取refs引用
高階組件中可獲取傳入組件的ref,通過ref獲取組件的實例(即拿到傳入組件實例的this),如下面的代碼,當程序初始化完成后調用原組件的log方法。
function refHOC(WrappedComponent) {return class Container extends Component {componentDidMount() {this.wapperRef.log()}render() {return <WrappedComponent {...this.props} ref={ref => { this.wapperRef = ref }} />;}} }注意:HOC包裹的組件默認無法在外部調用時拿到原組件refs引用
雖然高階組件的約定是將所有 props 傳遞給被包裝組件,但這對于 refs 并不適用。那是因為 ref 實際上并不是一個 prop。就像 key 一樣,它是由 React 專門處理的。如果將 ref 添加到 HOC 的返回組件中,則 ref 引用指向容器組件,而不是被包裝組件。
這個問題的解決方案是通過使用 React.forwardRef API(React 16.3 中引入)。
(3)抽象state
// 高階組件 function HOC(WrappedComponent) {return class Container extends React.Component {constructor(props) {super(props);this.state = {name: "",};this.onChange = this.onChange.bind(this);}onChange = (event) => {this.setState({name: event.target.value,})}render() {const newProps = {name: {value: this.state.name,onChange: this.onChange,},};return <WrappedComponent {...this.props} {...newProps} />;}}; }// 使用 class Example extends Component {render() {return <input name="name" {...this.props.name} />;} } export default HOC(Example) //或者 @HOC class Example extends Component {render() {return <input name="name" {...this.props.name} />;} }在這個例子中,我們把 input 組件中對 name這個prop在高階組件中進行了重定義的覆蓋(用value和onChange 代替),這就有效地抽象了同樣的 state 操作。使得input組件由非受控組件變成了受控組件
(4)操作組件的static方法
可以對傳入組件的static靜態方法進行獲取調用,增加、修改、刪除
function refHOC(WrappedComponent) {return class Container extends Component {componentDidMount() {//獲取static方法console.log(WrappedComponent.staticMethod)}//新增static方法WrappedComponent.addMethod1=()=>{}render() {return <WrappedComponent {...this.props} ref={ref => { this.wapperRef = ref }} />;}} }但當你將 HOC 應用于組件時,原始組件將使用容器組件進行包裝。這意味著容器組件默認沒有傳入組件的任何靜態方法,即無法在其他地方引入組件時拿到其靜態方法。所以與props同理,請務必將傳入組件的靜態方法拷貝到容器組件上
(5)根據props實現條件渲染
根據特定的props決定傳入組件是否渲染(如最上面的基本HOC例子)
function visibleHOC(WrappedComponent) {return class extends Component {render() {if (this.props.visible === false) return null;return <WrappedComponent {...props} />;}} }(6)用其他元素包裹傳入的組件
在HOC的容器組件中將原組件通過其他元素再包裹起來,從而實現布局或者修改樣式的目的:
function withBackgroundColor(WrappedComponent) {return class extends React.Component {render() {return (<div style={{ backgroundColor: "#ccc" }}><WrappedComponent {...this.props} {...newProps} /></div>);}}; }2.2 反向繼承
返回一個組件,該組件繼承傳入組件,在render中調用原組件的render。
由于繼承了原組件,能通過this訪問到原組件的生命周期、props、state、render等,相比屬性代理它能操作更多的屬性。
這種實現方式下,HOC組件和傳入組件的生命周期調用順序與隊列類似(先進先出)
通過反向繼承實現的HOC,相比屬性代理具有以下額外的功能:
(1)渲染劫持
渲染劫持指的就是高階組件可以控制 WrappedComponent 的渲染過程,并渲染各種各樣的結果。我們可以在這個過程中在任何 React 元素輸出的結果中讀取、增加、修改、刪除 props,或讀取或修改 React 元素樹,或條件顯示元素樹,又或是用樣式控制包裹元素樹。
上面屬性代理提到的條件渲染,其實也是渲染劫持的一種實現。
如果元素樹中包括了函數類型的 React 組件,就不能操作組件的子組件
渲染劫持實示例:
function hijackHOC(WrappedComponent) {return class extends WrappedComponent {render() {const tree = super.render();let newProps = {};if (tree && tree.type === "input") {newProps = { value: "渲染被劫持了" };}const props = Object.assign({}, tree.props, newProps);const newTree = React.cloneElement(tree, props, tree.props.children);return newTree;}} }(2)劫持傳入組件生命周期
因為反向繼承方式實現的高階組件返回的新組件是繼承于傳入組件,所以當新組件定義了同樣的方法時,將會會覆蓋父類(傳入組件)的實例方法,如下面代碼所示:
function HOC(WrappedComponent){// 繼承了傳入組件return class HOC extends WrappedComponent {// 注意:這里將重寫 componentDidMount 方法componentDidMount(){...}render(){//使用 super 調用傳入組件的 render 方法return super.render();}} }(3)操作傳入組件state
反向繼承方式實現的高階組件中可以讀取、編輯和刪除傳入組件實例中的 state,如下面代碼所示:
function debugHOC(WrappedComponent) {return class extends WrappedComponent {render() {console.log("props", this.props);console.log("state", this.state);return (<div className="debuging">{super.render()}</div>)}} }操作傳入組件的state可能會讓 WrappedComponent 組件內部狀態變得一團糟。大部分的高階組件都應該限制讀取或增加 state,尤其是后者,可以通過重新命名 state,以防止混淆。
2.3 兩種方式對比
- 屬性代理是從“組合”的角度出發,這樣有利于從外部去操作 WrappedComponent,可以操作的對象是 props,或者在 WrappedComponent 外面加一些攔截器,控制器等。
- 反向繼承則是從“繼承”的角度出發,是從內部去操作 WrappedComponent,也就是可以操作組件內部的 state ,生命周期,render函數等等。
3. 高階組件實際應用
(1)邏輯復用
多個頁面組件存在代碼結構和需求相似的情況,只是一些傳參和數據不同,存在較多重復性代碼。使用高階組件進行統一包裹封裝即可
下面是兩個結構和需求相似的頁面組件:
// views/PageA.js import React from "react"; import fetchMovieListByType from "../lib/utils"; import MovieList from "../components/MovieList";class PageA extends React.Component {state = {movieList: [],}/* ... */async componentDidMount() {const movieList = await fetchMovieListByType("comedy");this.setState({movieList,});}render() {return <MovieList data={this.state.movieList} emptyTips="暫無喜劇"/>} } export default PageA; // views/PageB.js import React from "react"; import fetchMovieListByType from "../lib/utils"; import MovieList from "../components/MovieList";class PageB extends React.Component {state = {movieList: [],}// ...async componentDidMount() {const movieList = await fetchMovieListByType("action");this.setState({movieList,});}render() {return <MovieList data={this.state.movieList} emptyTips="暫無動作片"/>} } export default PageB;將重復邏輯抽離成一個HOC:
// HOC import React from "react"; const withFetchingHOC = (WrappedComponent, fetchingMethod, defaultProps) => {return class extends React.Component {async componentDidMount() {const data = await fetchingMethod();this.setState({data,});}render() {return (<WrappedComponent data={this.state.data} {...defaultProps} {...this.props} />);}} }使用示例:
// 使用: // views/PageA.js import React from "react"; import withFetchingHOC from "../hoc/withFetchingHOC"; import fetchMovieListByType from "../lib/utils"; import MovieList from "../components/MovieList"; const defaultProps = {emptyTips: "暫無喜劇"}export default withFetchingHOC(MovieList, fetchMovieListByType("comedy"), defaultProps);// views/PageB.js import React from "react"; import withFetchingHOC from "../hoc/withFetchingHOC"; import fetchMovieListByType from "../lib/utils"; import MovieList from "../components/MovieList"; const defaultProps = {emptyTips: "暫無動作片"}export default withFetchingHOC(MovieList, fetchMovieListByType("action"), defaultProps);;// views/PageOthers.js import React from "react"; import withFetchingHOC from "../hoc/withFetchingHOC"; import fetchMovieListByType from "../lib/utils"; import MovieList from "../components/MovieList"; const defaultProps = {...}export default withFetchingHOC(MovieList, fetchMovieListByType("some-other-type"), defaultProps);上面設計的高階組件 withFetchingHOC,把不一樣的部分(組件和獲取數據的方法) 抽離到外部作為傳入,從而實現頁面的復用。
(2)權限控制
function auth(WrappedComponent) {return class extends Component {render() {const { visible, auth, display = null, ...props } = this.props;if (visible === false || (auth && authList.indexOf(auth) === -1)) {return display}return <WrappedComponent {...props} />;}} }authList是我們在進入程序時向后端請求的所有權限列表,當組件所需要的權限不在傳入權限列表中,或者設置的 visible是false,我們將其顯示為傳入的組件樣式,或者null。我們可以將任何需要進行權限校驗的組件應用HOC:
@authclass Input extends Component { ... }@authclass Button extends Component { ... }<Button auth="user/addUser">添加用戶</Button><Input auth="user/search" visible={false} >添加用戶</Input>4. 其他技巧:
(1)高階組件參數
有時,我們調用高階組件時需要傳入一些參數,這可以用非常簡單的方式來實現:
import React, { Component } from "React"; function HOCFactoryFactory(...params) { // 可以做一些改變 params 的事return function HOCFactory(WrappedComponent) { return class HOC extends Component { render() { return <WrappedComponent {...this.props} />; } } } }當你使用的時候,可以這么寫:
HOCFactoryFactory(params)(WrappedComponent) // 或者 @HOCFatoryFactory(params) class WrappedComponent extends React.Component{}(2)高階組件命名
當包裹一個高階組件時,我們失去了原始 WrappedComponent 的 displayName,而組件名字是方便我們開發與調試的重要屬性
HOC.displayName = `HOC(${getDisplayName(WrappedComponent)})`; // 或者 class HOC extends ... { static displayName = `HOC(${getDisplayName(WrappedComponent)})`; ...然后通過HOC.displayName來獲取即可
總結
以上是生活随笔為你收集整理的React 高阶组件HOC详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java72-GUL流式布局管理器
- 下一篇: 艺赛旗(RPA)Numpy 入门学习