React Navigation源代码阅读 : views/withNavigation.js

import React from 'react';
import propTypes from 'prop-types';
import hoistStatics from 'hoist-non-react-statics';

/**
 * HOC,增强一个组件,让其具有 navigation 属性
 * @param Component
 */
export default function withNavigation(Component) {
  class ComponentWithNavigation extends React.Component {
    static displayName = `withNavigation(${Component.displayName ||
      Component.name})`;

    static contextTypes = {
      navigation: propTypes.object.isRequired,
    };

    render() {
      const { navigation } = this.context;
      return (
        <Component
          {...this.props}
          navigation={navigation}
          ref={this.props.onRef}
        />
      );
    }
  }

  // 静态方法复制, 源组件 Component 的静态方法复制到 容器组件 ComponentWithNavigation 上面
  return hoistStatics(ComponentWithNavigation, Component);
}

猜你喜欢

转载自blog.csdn.net/andy_zhang2007/article/details/80380957