react-native 中将设计稿px单位转为dp

在utils文件中新建styleKits.js
import { Dimensions } from "react-native";

// 设计稿宽度 / 元素的宽度 = 手机屏幕 / 手机中的元素宽度

// =》   手机中的元素宽度 = 手机屏幕宽度 * 元素的宽度 / 设计稿的宽度

const screeWidth = Dimensions.get("window").width

/**
 * 将px转为dp
 * @param {Number} elePx 元素的宽度或高度, 单位 px
 * @returns 
 */
export const pxToDp = (elePx) => {
    return  screeWidth * elePx / 375 //这里假设设计稿宽度是375
}

使用

import { pxToDp } from "../../utils/stylesKits";
<View style={{ padding: pxToDp(20) }}></View>

 

posted @ 2022-08-29 14:00  龙卷风吹毁停车场  阅读(117)  评论(0)    收藏  举报