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

import React from 'react';
import {Dimensions} from 'react-native';
import hoistNonReactStatic from 'hoist-non-react-statics';

/**
 * 输入当前屏幕宽度高度参数,判断是横屏还是竖屏,如果 宽width 大于 高height ,
 * 认为是横屏,否则认为是竖屏
 * @param width
 * @param height
 * @return {boolean} 横屏时返回 true,竖屏时返回 false
 */
export const isOrientationLandscape = ({width, height}) => width > height;

/**
 * HOC,对一个组件进行封装,使其带有屏幕方向识别能力
 * @param WrappedComponent
 */
export default function (WrappedComponent) {
    class withOrientation extends React.Component {
        constructor() {
            super();

            // 初始状态
            const isLandscape = isOrientationLandscape(Dimensions.get('window'));
            this.state = {isLandscape};
        }

        componentDidMount() {
            // 添加屏幕尺寸变化事件监听器
            Dimensions.addEventListener('change', this.handleOrientationChange);
        }

        componentWillUnmount() {
            // 删除屏幕尺寸变化事件监听器
            Dimensions.removeEventListener('change', this.handleOrientationChange);
        }

        /**
         * 屏幕尺寸变化事件监听器逻辑 : 屏幕方向发生变化时更新当前组件状态 isLandscape (是否横屏)
         * @param window
         */
        handleOrientationChange = ({window}) => {
            const isLandscape = isOrientationLandscape(window);
            this.setState({isLandscape});
        };

        render() {
            return <WrappedComponent {...this.props} {...this.state} />;
        }
    }

    // 静态方法提升:
    // 使用HOC对一个组件进行封装时,静态方法并不会被复制到HOC上,但是这部分信息
    // 不能丢失,下面的 hoistNonReactStatic 语句负责复制 WrappedComponent 上的
    // 静态方法到 HOC withOrientation 上
    return hoistNonReactStatic(withOrientation, WrappedComponent);
}

猜你喜欢

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