Higher-Order Components

    具体来说,高阶组件是一个函数,能够接受一个组件并返回一个新的组件。

    组件是将props转化成UI,然而高阶组件将一个组价转化成另外一个组件。

    React在第三方组件库中非常常见,例如Redux的和Relay’screateContainer

    在这篇文档中,我们将讨论高阶组件为什么非常有用,并且如何构建。

    组件是React中代码重用的最小单元。然而你会发现某些模式并不能直接适应传统组件。

    例如,假设你有一个接受外部数据源渲染评论列表的CommentList组件:

    1. class CommentList extends React.Component {
    2. constructor() {
    3. super();
    4. this.handleChange = this.handleChange.bind(this);
    5. this.state = {
    6. // "DataSource" is some global data source
    7. comments: DataSource.getComments()
    8. };
    9. }
    10. componentDidMount() {
    11. // Subscribe to changes
    12. DataSource.addChangeListener(this.handleChange);
    13. }
    14. componentWillUnmount() {
    15. // Clean up listener
    16. DataSource.removeChangeListener(this.handleChange);
    17. }
    18. handleChange() {
    19. // Update component state whenever the data source changes
    20. this.setState({
    21. comments: DataSource.getComments()
    22. });
    23. }
    24. render() {
    25. return (
    26. <div>
    27. {this.state.comments.map((comment) => (
    28. <Comment comment={comment} key={comment.id} />
    29. ))}
    30. </div>
    31. );
    32. }
    33. }

    随后,你编写一个订阅单个博文的组件,其遵循类似的模式:

    1. class BlogPost extends React.Component {
    2. constructor(props) {
    3. super(props);
    4. this.handleChange = this.handleChange.bind(this);
    5. this.state = {
    6. blogPost: DataSource.getBlogPost(props.id)
    7. };
    8. }
    9. componentDidMount() {
    10. DataSource.addChangeListener(this.handleChange);
    11. }
    12. componentWillUnmount() {
    13. DataSource.removeChangeListener(this.handleChange);
    14. }
    15. handleChange() {
    16. this.setState({
    17. blogPost: DataSource.getBlogPost(this.props.id)
    18. });
    19. }
    20. return <TextBlock text={this.state.blogPost} />;
    21. }
    22. }

    CommentListBlogPost是等价的,除了它们调用DataSource的不同方法,有不同的输出。但它们大部分的实现是类似的:

    • 组件mount结束后,都添加DataSource的change监听
    • 除了监听函数,无论什么时候datasource改变之后,都会调用setState
    • 组件unmount之后,都会移除监听。

    你可以想象在一个大型项目中,订阅DataSource并调用setState的函数将会一次次出现。我们需要将其抽象出来,使得我们能够在一个地方定义逻辑并且在我们的组件中共享。这就是高阶组件的优点。

    我们可以写一个函数,能够创建类似于CommentListBlogPost这类订阅DataSource的新的组件。这个函数接受一个子组件作为参数,这个子组件接受订阅数据源作为props,调用withSubscription如下:

    1. const CommentListWithSubscription = withSubscription(
    2. CommentList,
    3. (DataSource) => DataSource.getComments()
    4. );
    5. const BlogPostWithSubscription = withSubscription(
    6. BlogPost,
    7. (DataSource, props) => DataSource.getBlogPost(props.id)
    8. });

    第一个参数是被包含的组件,第二个参数根据给定的DataSource和当前的props取回我们需要的数据。

    CommentListWithSubscriptionCommentListWithSubscription被渲染时,CommentListBlogPost将会被传递data属性,其中包含从DataSource取回的最新数据。

    1. // This function takes a component...
    2. function withSubscription(WrappedComponent, selectData) {
    3. // ...and returns another component...
    4. return class extends React.Component {
    5. constructor(props) {
    6. super(props);
    7. this.handleChange = this.handleChange.bind(this);
    8. this.state = {
    9. data: selectData(DataSource, props)
    10. };
    11. }
    12. componentDidMount() {
    13. // ... that takes care of the subscription...
    14. DataSource.addChangeListener(this.handleChange);
    15. }
    16. componentWillUnmount() {
    17. DataSource.removeChangeListener(this.handleChange);
    18. }
    19. handleChange() {
    20. this.setState({
    21. data: selectData(DataSource, this.props)
    22. });
    23. }
    24. render() {
    25. // ... and renders the wrapped component with the fresh data!
    26. // Notice that we pass through any additional props
    27. return <WrappedComponent data={this.state.data} {...this.props} />;
    28. }
    29. };
    30. }

    高阶组件既不会修改输入组件,也不会通过继承来复制行为。相反,通过包裹的形式,高阶组件将原先的组件组合在container组件中。高阶组件是纯函数,没有副作用。

    就是这样。被包裹的元素接受container的所有props和新的props,并使用其渲染输出。高阶组件并不关心数据将会如何或者为什么使用,并且被包裹的元素并不关心数据的源头。

    和组件相类似,withSubscription和被包裹组件的联系是基于props的。只要为被包裹元素提供相同的属性,那么很容易将一个高阶组件组件转化成不同的高阶组件。例如,如果你想要改变数据获取的库,这将非常有用。

    不要改变原始组件,而是使用组合

    要忍住在高阶组件修改组件原型(或者修改其他)的冲动。

    1. function logProps(InputComponent) {
    2. InputComponent.prototype.componentWillReceiveProps(nextProps) {
    3. console.log('Current props: ', this.props);
    4. console.log('Next props: ', nextProps);
    5. }
    6. // The fact that we're returning the original input is a hint that it has
    7. // been mutated.
    8. return InputComponent;
    9. }
    10. // EnhancedComponent will log whenever props are received
    11. const EnhancedComponent = logProps(InputComponent);

    这里存在一些问题,一个是输入组件(InputComponent)不能脱离增强组件分别重用。更重要的是,如果将另一个也修改componentWillReceiveProps的高阶组件应用于EnhancedComponent组件,第一个高阶组件的功能将会别覆盖。这个高阶组件对函数组件不会起作用,因为函数组件没有生命周期函数。

    具有修改功能的高阶组件是一个漏洞的抽象过程:用户必须知道它是怎么实现的从而避免与其他高阶组件的冲突。

    相比于修改,高阶组件最好是通过将输入组件包裹在容器组件的方式来使用组合:

    这个高阶组件与之前的修改原型的版本有着相同的功能,但又避免了潜在的冲突可能。其在class类型和函数类型的组件都起作用。并且,因为是纯函数,它可以与其他高阶组件,甚至是自己组合。

    你可能已经注意到高阶组件和被称为容器组件(container components)的模式有相同之处。容器组件是分离责任策略的一部分。这个分离策略是关于高层次和低层次关注点之间的责任分离。容器管理着类似订阅和状态这类东西,和给组件传递属性来处理类似渲染UI这类事情。高阶组件使用容器作为其实现的一部分。你可以将高阶组件视为定义参数化容器组件。

    高阶组件可以向组件添加功能。他不应该大幅度地改变功能。期望地是高阶组件返回的组件和被包裹组件具有相似的界面。

    高阶组件应该通过props传递那些与特定功能无关的特性。大多数的高阶组件包含如下的render函数:

    1. render() {
    2. // Filter out extra props that are specific to this HOC and shouldn't be
    3. // passed through
    4. const { extraProp, ...passThroughProps } = this.props;
    5. // Inject props into the wrapped component. These are usually state values or
    6. // instance methods.
    7. const injectedProp = someStateOrInstanceMethod;
    8. // Pass props to wrapped component
    9. return (
    10. <WrappedComponent
    11. injectedProp={injectedProp}
    12. {...passThroughProps}
    13. />
    14. }

    这个约定帮助确定高阶组件能够足够灵活和可以被重用。

    约定: 最大化组合(Maximizing Composability)

    不是所有的高阶组件看起来都是一样的。有时候,它接受包裹组件作为单一参数:

    1. const NavbarWithRouter = withRouter(Navbar);

    通常情况下,高阶组件接受其他的参数。在Relay这个例子中,配置对象用来指定组件的数据依赖关系:

    1. const CommentWithRelay = Relay.createContainer(Comment, config);

    高阶组件最常见的签名如下:

    1. // React Redux's `connect`
    2. const ConnectedComment = connect(commentSelector, commentActions)(Comment);

    什么?!,如果你把它分开,就更容易看到发生了什么。

    1. // connect is a function that returns another function
    2. const enhance = connect(commentListSelector, commentListActions);
    3. // The returned function is an HOC, which returns a component that is connected
    4. // to the Redux store
    5. const ConnectedComment = enhance(CommentList);

    总的来说,connect是一个返回高阶组件的高阶函数!

    这种形式看起来是混乱的或者是没有必要的,但是它是一个有用的属性。单参数的高阶组件类似于connect函数所返回的函数,其签名为Component => Component。返回的函数的输出类型和输入类型是相同的,很容易相互组合。

    包括lodash(例如)、Redux和在内的许多第三方库都提供了组合函数。

    由高阶属性创建的容器组件在React开发者工具中显示同其他的组件相似。为了方便调试,选择一个显示名称(display name),表示它是高阶组件的结果。

    最常见的方法是给被包裹元素包裹一个显示名称(display name)。因此,如果你的高阶组件名字为withSubscription,被包裹的元素名称为CommentList,那就选择名称为WithSubscription(CommentList)

    1. function withSubscription(WrappedComponent) {
    2. class WithSubscription extends React.Component {/* ... */}
    3. WithSubscription.displayName = `WithSubscription(${getDisplayName(WrappedComponent)})`;
    4. return WithSubscription;
    5. }
    6. function getDisplayName(WrappedComponent) {
    7. return WrappedComponent.displayName || WrappedComponent.name || 'Component';
    8. }

    警告

    高阶组件有以下几个警告,如果你是刚接触React,这些警告可能不会立刻就被发现。

    React的diff算法(又称为reconciliation)使用组件标识符(component identity)来决定是否应该更新已有的子树或者将其抛出并安装一个新的子树。如果从render返回的组件等同于(===)之前render函数返回的组件,React将会迭代地通过diff算法更新子树到新的子树。如果不相等,则先前的子树将会完全卸载。

    通常情况下,你不需要考虑这些。但是这对高阶组件非常重要,因为这意味你在组件的render方法中不能通过高阶组件产生组件:

    1. render() {
    2. // A new version of EnhancedComponent is created on every render
    3. // EnhancedComponent1 !== EnhancedComponent2
    4. const EnhancedComponent = enhance(MyComponent);
    5. // That causes the entire subtree to unmount/remount each time!
    6. return <EnhancedComponent />;
    7. }

    这个问题不仅仅关乎于性能,卸载组件会造成组件状态和其子元素全部丢失。

    相反地,在组件定义外应用高阶组件,以便生成的组件只会被创建一次。然后,它的标识符在每次渲染中都是相同的。无论如何,这才是你想要的。

    在一些极少的例子中你需要动态地引用高阶组件,你可以在组件的声明周期函数中使用或者在构造函数中使用。

    有时候,在React组价中定义静态方法是非常有用的。例如,Relay容器对外暴露一个静态方法getFragment,来帮助组合GraphQL代码。

    当你将一个组件应用于高阶组件式,虽然原有的组件被容器组件所包裹,但这以为这新的组件没有之前组件的静态函数。

    1. // Define a static method
    2. WrappedComponent.staticMethod = function() {/*...*/}
    3. // Now apply an HOC
    4. const EnhancedComponent = enhance(WrappedComponent);
    5. // The enhanced component has no static method
    6. typeof EnhancedComponent.staticMethod === 'undefined' // true

    为了解决这个问题,在返回之前,可以向容器组件中复制原有的静态方法:

    1. function enhance(WrappedComponent) {
    2. class Enhance extends React.Component {/*...*/}
    3. // Must know exactly which method(s) to copy :(
    4. Enhance.staticMethod = WrappedComponent.staticMethod;
    5. return Enhance;
    6. }

    然而,这需要你明确地知道哪些方法需要别复制。你可以使用hoist-non-react-statics来自动复制非React的静态方法。

    1. import hoistNonReactStatic from 'hoist-non-react-statics';
    2. function enhance(WrappedComponent) {
    3. class Enhance extends React.Component {/*...*/}
    4. hoistNonReactStatic(Enhance, WrappedComponent);
    5. return Enhance;
    6. }

    另一个有效的方法是将静态方法与组件本身相分离:

    尽管惯例是高阶组件会给被包裹组件传递所有的属性(props),但是不会传递refs。因为ref不是一个属性,就像key一样,它是由React特殊处理的。如果你给高阶组件产生的组件的元素添加ref,ref引用的是外层的容器组件的实例,而不是被包裹的组件。

    如果你遇到这个问题,最好的解决方法是避免使用ref。有时候,React新手用户依赖于refs,这时候props是更好的选择。

    1. function Field({ inputRef, ...rest }) {
    2. return <input ref={inputRef} {...rest} />;
    3. }
    4. // Wrap Field in a higher-order component
    5. const EnhancedField = enhance(Field);
    6. // Inside a class component's render method...
    7. <EnhancedField
    8. inputRef={(inputEl) => {
    9. // This callback gets passed through as a regular prop
    10. this.inputEl = inputEl
    11. }}
    12. />
    13. // Now you can call imperative methods

    无论如何,这都是一个完美的解决方案。我们倾向于refs是由库去处理,而不是要求你手动地处理。我们正在寻找解决这个问题的办法,以便在使用高阶组件时不需要注意这个问题。