RN屏幕适配方案

1,103 阅读1分钟

对不同尺寸手机屏幕做适配

方法一 最常规方式可以用RN官方提供的DimensionsAPI。

import { Dimensions } from "react-native";
const deviceWidthDp = Dimensions.get("window").width;
// 默认设计稿375
const uiWidthPx = 375;
function dp2px(uiElementPx) {
    return (uiElementPx * deviceWidthDp) / uiWidthPx;
}
export default dp2px;

弊端:每处需要做适配的地方都要引入下公共方法,dp2px(10),dp2px(20)之类的。

方法二 自己封装StyleSheet

import { StyleSheet } from "react-native";
import dp2px from "./dp2px";

let MyStyleSheet = {
    create(style) {
        let s = { ...style };
        // 目前仅对以下的属性进行处理
        let list = [
            "width",
            "height",
            "marginTop",
            "marginBottom",
            "marginLeft",
            "marginRight",
            "paddingTop",
            "paddingRight",
            "paddingBottom",
            "paddingLeft",
            "top",
            "right",
            "bottom",
            "left",
            "fontSize",
            "lineHeight",
        ];
        for (let outKey in s) {
            for (let innerKey in s[outKey]) {
                if (
                    list.includes(innerKey) &&
                    typeof s[outKey][innerKey] == "number"
                ) {
                    s[outKey][innerKey] = dp2px(s[outKey][innerKey]);
                }
            }
        }
        return StyleSheet.create(s);
    },
};
export default MyStyleSheet;

需要引入的时候如下

import MyStyleSheet from "./myStyleSheet";

// 使用封装好的MyStyleSheet来代替原生StyleSheet,直接写数字即可自动转换为不同屏幕适配的dp
let style = MyStyleSheet.create({
    title: {
        fontSize: 14,
        width: 100,
    },
    subTitle: {
        paddingTop: 10,
        paddingBottom: 10,
        marginTop: 10,
        marginBottom: 10,
    },
});

弊端:尝试了后发现只能修改styleSheet层面的样式文件,无法去修改内联样式

方案三 babel层面去实现

看到网上有个人从babel层面去实现这屏幕适应插件,自己没尝试过,不知道具体使用效果如何,待定方案

https://www.npmjs.com/package/@hancleee/babel-plugin-react-native-pxtodp


参考资料

juejin.cn/post/730678…

juejin.cn/post/688933…