rn 开发过程中样式适配

108 阅读2分钟
/*
 * @Author:
 * @Description: '设备常量'
 * @Last Modified time:
 * @ToDo: ''
 */

import { Platform, Dimensions, StatusBar } from 'react-native'

// let ExtraDimensions = Platform.OS === 'android' ? require('react-native-extra-dimensions-android') : null

// 因为不会更新,导致宽度异常,不建议使用
const DEVICE_WIDTH = Dimensions.get('window').width
const DEVICE_HEIGHT = Dimensions.get('window').height

// 建议使用下面方法(不要在StyleSheet里调用,否则等同与上面写法)
const GET_DEVICE_WIDTH = () => {
	return Dimensions.get('window').width
}

const GET_DEVICE_HEIGHT = () => {
	return Dimensions.get('window').height
}

// 是否是ios
const IS_IOS = Platform.OS === 'ios'

// 是否是iphonex 系列
const IS_IPHONEX_SERIES =
	Platform.OS === 'ios' && Number((DEVICE_HEIGHT / DEVICE_WIDTH + '').substring(0, 3)) * 100 === 216

//顶部状态栏的高度
export const StatusBarHeight = getStatusBarHeight()

//底部 bottom安全区域高度
export const SafeAreaBottomHeight = IS_IPHONEX_SERIES ? 24 : 0

// 导航高度
const NAVIGATION_HEIGHT = 44.0

/**
 * 状态栏的高度
 */
export function getStatusBarHeight() {
	if (Platform.OS === 'android') {
		return StatusBar.currentHeight || 20
	}
	if (IS_IPHONEX_SERIES) {
		return 44
	}
	return 20
}

// 设计稿尺寸
const BASE_WIDTH = 375
const BASE_HEIGHT = 812

// 横向缩放:根据设计稿宽度缩放
export const w = (size: number) => (DEVICE_WIDTH / BASE_WIDTH) * size

// 纵向缩放:根据设计稿高度缩放
export const h = (size: number) => (DEVICE_HEIGHT / BASE_HEIGHT) * size
/**
 * 
 *元素宽高,图片,布局块 1  (完全按屏幕比例缩放,保持整体布局一致)
 字体,圆角,padding, margin    0.5, 适中缩放,不让文字或者间距放大过头,保证可读性
 保持设计稿尺寸(不缩放)     0      元素不受屏幕尺寸影响,固定大小
 */
// 适中缩放:横向缩放和原始尺寸的折中,可调 factor,默认 0.5
export const wh = (size: number, factor = 0.5) => size + (w(size) - size) * factor

const DeviceConstant = {
	DEVICE_WIDTH,
	DEVICE_HEIGHT,
	GET_DEVICE_HEIGHT,
	GET_DEVICE_WIDTH,
	IS_IOS,
	NAVIGATION_HEIGHT,
	IS_IPHONEX_SERIES,
	StatusBarHeight,
	SafeAreaBottomHeight,
}

export default DeviceConstant

在样式书写过程中,只需要根据设计稿写 width: w(375), height: h(812) fontSize: wh(16) 等就可以

wh使用方式:

image.png

注意书写过程中,一些外层元素的高度最好写minHeihgt: h() 避免造成文字显示垂直方向上显示不全。

当一个元素使用定位 position: 'absolute' ,它的父元素 不能使用 justcontent: 'center',alignItem: 'center' 这样的属性,会导致定位失效

尽量不要写paddingBootom paddingTop 而是设置宽高,然后flex 适配。