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

本文介绍了一个React Native应用中用于检测屏幕方向并封装为高阶组件(HOC)的方法。该方法通过监听屏幕尺寸的变化来实时更新组件的状态,从而实现横屏与竖屏的自动切换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值