ReactNative 基础 - 04 (自定义rpx)

暨成双
2023-12-01

        rpx(responsive pixel): 可以根据屏幕宽度进行自适应。规定屏幕宽为750rpx。如在 iPhone6 上,屏幕宽度为375px,共有750个物理像素,则750rpx = 375px = 750物理像素,1rpx = 0.5px = 1物理像素。

      ReactNative 中没有rpx单位,使用公式计算出来,封装为一个函数使用,例如:rpx(20) = 20rpx

1、获取屏幕宽度:通过Dimensions获取

        Dimensions.get('window'):window比screen高度适应性更好,会自动去掉导航栏、状态栏...的高度,获取到的是可操作区

2、计算rpx

import React, {Component} from 'react';
import {Text, View, Dimensions} from 'react-native';

const {width, height} = Dimensions.get('window');
const rpx = x => (width / 750) * x;
export default class App extends Component {
  render() {
    console.log(width, height);
    return (
      <View>
        <Text style={{fontSize: rpx(46)}}> OOOOOO </Text>
      </View>
    );
  }
}

 类似资料: