前言
最近一直在做react-native相关的开发,但是发现移动端自适应适配是个很大的痛点,前后用过3种方案,最后在团队中落地最后一种方案
-
px2dp 在公共的地方写了一个公共的方法,像这样
// UI图设计基准大小 const uiWidthPx = 750 function px2dp(uiElementPx: number) { if (screenWidth > screenHeight) { return (uiElementPx * screenHeight) / uiWidthPx } return (uiElementPx * screenWidth) / uiWidthPx } // 使用的时候 const styles = StyleSheet.create({ name:{ width:px2dp(200) } })这个方法有两个弊端,每个用到的文件都要单独去引入一次,并且每个尺寸要用px2dp来转,这就很繁琐
-
后来找了另外一种方案,封装 CustomStyleSheet代替原生 StyleSheet,具体可以看一下 一文解决React-Native的屏幕适配,这个也有两个弊端,每个用到的文件要单独引入CustomStyleSheet,并且行内样式没法转,不过可以减少一些px2dp的植入
-
目前在用的方案,写了一个babel插件github源码地址
插件babel-plugin-px2dp
相当于针对特定样式属性,比如 width,height,进行自动适配,支持 形如
10、"10rpx"、`${10 + 10}rpx`,
这个插件会把
import React from "react";
import { View, StyleSheet } from "react-native";
export const Test = () => {
const fontSize = 10 + 10;
return <View size={`${10 + 10}rpx`} fontSize={`${fontSize}rpx`} style={styles.container} />;
};
const styles = StyleSheet.create({
container: {
width: 200,
fontSize: "10rpx",
backgroundColor: "pink"
}
});
转换为
import { Dimensions } from "react-native";
import React from "react";
import { View, StyleSheet } from "react-native";
export const Test = () => {
const fontSize = 10 + 10;
return <View size={Dimensions.get('window').width * (10 + 10) / 750} fontSize={Dimensions.get('window').width * fontSize / 750} style={styles.container} />;
};
const styles = StyleSheet.create({
container: {
width: Dimensions.get('window').width * 200 / 750,
fontSize: Dimensions.get('window').width * 10 / 750,
backgroundColor: "pink"
}
});
这样的好处是什么呐,不用每次手动引入额外的方法,只要写尺寸,或者像web那样代入rpx单位即可
如何使用
yarn add @jswangtao/babel-plugin-px2dp
在 babel.config.js 中添加插件配置
[
"@jswangtao/px2dp",
{
uiWidth: 750, // ui设计稿宽度
includes: ["pages"], // 插件生效的文件夹
excludes: [] // 插件不生效的文件夹
}
]