引入:Dimensions
import { Dimensions } from 'react-native';
原理
1.获取使用者设备的宽高。
2.确定设计图的宽高。
3.计算出比例:设备的宽高/设计图的宽高 == 比例 ,假设获取到的设备的宽为400,而我们设计图为375那这个比例就是400/375 = 1.06666666...
示例
import React, { useEffect } from 'react';
import { View, Text, StyleSheet, Dimensions } from 'react-native';
function ChangeWater() {
useEffect(() => {
//一些只需要发起一次的请求...
}, [])
//逻辑代码...
return (
<View style={styles.box}>
<View style={styles.top}></View>
<View>
<Text>2023/09/13</Text>
</View>
{/* 其他的页面代码 */}
</View>
);
}
//获取手机页面的宽高
const { width, height } = Dimensions.get('window');
//设定ui设计的宽高
const widthPx = 390;
const heightPx = 844;
const w = (value) => {
return (value * width) / widthPx
}
const h = (value) => {
return (value * height) / heightPx
}
const styles = StyleSheet.create({
box: {
paddingTop: h(96),
width: w(390),
height: h(844)
},
top:{
padding: w(10),
marginLeft: w(20),
marginTop: h(15),
}
})
export default ChangeWater;
小知识
在算法(value * width) / widthPx中写法是可以多样性的,没有规定必须是那一种写法,就比如10*2/2 == 10, 10/2*2 == 10 ,2/2*10 == 10 所以算法怎么写不重要,重要的是最后的答案是自己需要的。