高阶组件

作者: yuzhiyi_宇 | 来源:发表于2018-06-16 16:21 被阅读64次

如果一个函数操作其他函数,即将其他函数作为参数或将函数作为返回值,将其称为高阶函数。高阶组件(high-order component)类似于高阶函数,接收 React 组件作为输入,输出一个新的 React 组件。高阶组件让代码更具有复用性、逻辑性与抽象特征。可以对 render 方法作劫持,也可以控制 props 与 state。

实现高阶组件的方法有如下两种。

  1. 属性代理(props proxy)。属性组件通过被包裹的 React 组件来操作 props。
  2. 反向代理(inheritance inversion)。高阶组件继承于被包裹的 React 组件。

1. 属性代理

属性代理是常见高阶组件的实现方法。

const MyContainer = (WrappedComponent) => {
    return class extends Component {
        render() {
            return (
                <WrappedComponent
                    {...props}
                />
            )
        }
    }
}

export default MyContainer;

在 render 方法中返回传入 WrappedComponent 的 React 组件。这样就可以通过高阶组件来传递 props,这种方法即为属性代理。

原始组件想要具备高阶组件对它的修饰,有两种方式。
方式一:

export default MyContainer;

class MyComponent extends Component {
}

export default MyContainer(MyComponent);

方式二:
ES7 添加了 decorator 的属性,我们可以通过 decorator 来转换,以此简化高阶组件的调用。

@MyContainer
class MyComponent extends Component {
}

export default MyComponent;

这样组件就可以一层层地作为参数被调用,原始组件就具备了高阶组件对它的修饰。这样保持了单个组件封装性的同时还保留了易用性。
生命周期:
didmount -> HOC didmount -> (HOCs didmount) ->(HOCs will unmount) -> Hoc will unmount -> unmount
功能上,高阶组件可以控制 props、通过 refs 使用引用、抽象 state 和使用其他元素包裹 WrappedComponent。

  • 控制 props
    我们可以读取、增加、编辑或是移除从 WrappedComponent 传进来的 props,但需要小心删除与编辑重要的 props。应该尽量对高阶组件的 props 作新的命名以防止混淆。
const MyContainer = (WrappedComponent) => {
    return class extends Component {
        render() {
            const newProps = {
                text: newText
            };
            return (
                <WrappedComponent
                    {...props}
                    {...newProps}
                />
            )
        }
    }
}

export default MyContainer;

当调用该高阶组件时,就可以使用 text 这个新的 props了。

  • 通过 refs 使用引用
    在高阶组件中,可以接受 refs 使用 WrappedComponent 的引用。
const MyContainer = (WrappedComponent) => {
    return class extends Component {
        ref = (view) => {
            view.mentod();
        }
        render() {
            const props = Object.assign({}, this.props, {
                ref: this.ref
            });
            return (
                <WrappedComponent
                    {...props}
                />
            )
        }
    }
}

export default MyContainer;

当 WrappedComponent 被渲染时,refs 回调函数就会被执行,这样就会拿到一份 WrappedComponent 实例的引用。这就可以方便地用于读取或增加实例的 props,并调用实例的方法。

  • 抽象 state
    可以通过 WrappedComponent 提供的 props 和回调函数抽象 state。将原组件抽象为展示型组件,分离内部状态 。

const MyContainer = (WrappedComponent) => {
    return class extends Component {
        constructor(props);
        super(props);
        this.state = {
            name: ''
        };
    }

    onNameChange(text) {
        this.setState({
            name: text
        });
    }

    render() {
        const newProps =  {
            name = {
                value: this.state.name,
                onChangeText: {this.onNameChange}
            }
        }
        return (
            <WrappedComponent
                {...this.props}
                {...newProps}
            />
        );
    }
}

export default MyContainer;

使用

@MyContainer
class MyComponent extends Component {
    render() {
        return (
            <TextInput
                {...this.props.name}
            />
        );
    }
}
  • 使用其他元素包裹 WrappedComponent
    可以使用其他元素包裹 WrappedComponent。
export default LoginPleaseMixin;

const MyContainer = (WrappedComponent) => {
    return class exrends PureComponent {
        render() {
            return (
                <View>
                    <WrappedComponent />
                </View>
            );
        }
    }
}

export default MyContainer;

2. 反向继承

反向继承是另一种构建高阶组件的方法。

const MyContainer = (WrappedComponent) => {
    return class extends WrappedComponent {
        render() {
            return super.render();
        }
    }
}

export default MyContainer;

高阶组件返回的组件继承于 WrappedComponent。因为被动地继承了 WrappedComponent,所有的调用都会反向。
通过继承 WrappedComponent 来实现,方法可以通过 super 来顺序调用。因为依赖于继承的机制,HOC 的调用顺序和队列是一样的:
didmount -> HOC didmount -> (HOCs didmount) -> will unmount -> HOC will unmount -> (HOCs will unmount)
在反向继承方法中,高阶组件可以使用 WrappedComponent 引用,这意味着它可以使用 WrappedComponent 的 state、props、生命周期和render方法,但他不能保证完整的子组件树被解析。

  • 渲染劫持
    渲染劫持指的就是高阶组件可以控制 WrappedComponent的渲染过程,并渲染各种各样的结果。我们可以在这个过程中在任何 React 元素输出的结果中读取、增加、修改、删除 props,或读取或修改 React 元素树、或条件显示元素树,又或是用样式控制包裹元素树。
    反向继承不能保证完整的子组件树被解析,这意味着将限制渲染劫持功能。但是如果元素树包裹了函数类型的 React 组件,就不能操作组件的子组件。
    条件渲染:
const MyContainer = (WrappedComponent) => {
   return class extends WrappedComponent {
        render() {
            if (this.props.loggIn) {
                return super.render();
            } else {
                return null;
            }
        }
    }
}

export default MyContainer;

对 render 输出结果进行修改:

import React, {
} from 'react';
const MyContainer = (WrappedComponent) => {
    return class extends WrappedComponent {
        render() {
            const elementsTree = super.render();
            let newProps = {};
            if (elementsTree && elementsTree.type === 'input') {
                newProps = {value: 'may the force be with you'};
            }
            const props = Object.assign({}, elementsTree.props, newProps);
            const newElementsTree = React.cloneElement(elementsTree, props, elementsTree.props.children);
            return newElementsTree;
        }
    }
}

export default MyContainer;

我们可以做各种各样的事,甚至可以反转元素树,或是改变元素树中的 props。

  • 控制 state
    高阶组件可以读取、修改或删除 WrappedComponent 实例中的 state,如果需要的话,也可以增加 state。但是这样做,可能让 WrappedComponent组件内部状态变得一团糟。大部分的高阶组件都应该限制读取或增加 state,尤其是后者,可以通过重新命名 state,以防止混淆。
const MyContainer = (WrappedComponent) => {
    return class extends WrappedComponent {
        render() {
            return (
                <View>
                    <Text>
                        {JSON.stringify(this.props)}
                    </Text>
                    <Text>
                        {JSON.stringify(this.state)}
                    </Text>
                    {super.render()}
                </View>
           );
        }
    }
}

export default MyContainer;

3. 组件命名

当包裹一个高阶组件时,我们失去了原始的 WrappedComponent 的 displayName,而组件名字是方便我们开发与调试的重要属性。

HOC.displayName = `HOC{${getDisplayName(WrappedComponent)}}`;

class HOC extends ... {
    static displayName = `{Hoc(${getDisplayName(WrappedComponent)})}`

    function getDisplayName(WrappedComponent) {
        return WrappedComponent.displayName ||
            WrappedComponent.name ||
            'Component';
    }
}

4. 组件参数

调用高阶组件时需要传入一些参数,可以用简单方式实现。

function HOCFactoryFactory(...params) {
    return function HOCFactory(WrappedComponent) {
        return class HOC extends Component {
            render() {
                return (
                    <WrappedComponent 
                        {...this.props}
                    />
                );
            }
        }
    }
}

使用:

HOCFactoryFactory(params)(WrappedComponent)

或者

@HOCFactoryFactory(params)
class WrappedComponent extends Component {
}

相关文章

  • React-Native 高阶组件

    高阶函数 高阶组件(属性代理)普通组件还可以向高阶组件传值 高阶组件(反向继承) 普通组件的 static 方法怎...

  • React高阶组件HOC

    高阶组件本质是函数,参数是 组件1 返回组件2,高阶组件是为了复用通用逻辑高阶组件eg:import React,...

  • react与vue中高阶组件的对比

    由高阶函数引申出来的高阶组件 高阶组件本质上也是一个函数,并不是一个组件,且高阶组件是一个纯函数。高阶组件,顾名思...

  • 2021-08-05-🦕🦕 react 高阶组件hotc和@装饰

    简介 高阶组件可以直接调用子组件属性方法;子组件通过 this.props.xxx调用高阶组件方法属性 高阶组件无...

  • React——第三阶段(1)(高阶组件、context)

    根据胡子大哈的文章学习,感谢大胡分享胡子大哈-高阶组件、context 高阶组件 什么是高阶组件 高阶组件就是一个...

  • React 高阶组件(HOC)

    什么是高阶组件? 高阶组件(Higher-Order Components,简称HOC):简而言之,高阶组件就是加...

  • 高阶组件

    高阶组件 先来引入这个概念 高阶函数是什么? 高阶函数就是一个函数返回一个函数eg: 高阶组件 类同 高阶组件就是...

  • React 进阶之高阶组件

    高阶组件 HOC 高阶组件(HOC)是react中的高级技术,用来重用组件逻辑。但高阶组件本身并不是React A...

  • 利用 React 高阶组件实现一个面包屑导航

    什么是 React 高阶组件 React 高阶组件就是以高阶函数的方式包裹需要修饰的 React 组件,并返回处理...

  • Vue组件

    1,高阶组件:组件

网友评论

    本文标题:高阶组件

    本文链接:https://www.haomeiwen.com/subject/ekmreftx.html