React Native - 为不同屏幕大小提供样式响应性

3
我们正在开发一款应用,它将在多个设备(iOS、Android)上运行,因此要适应许多不同的屏幕尺寸。在阅读了PixelRatio之后,似乎没有一个神奇的解决方案可以自动缩放所有样式值来适应不同的屏幕尺寸。
我所能想到的唯一解决方案是重写Stylesheet类,自动根据当前屏幕尺寸缩放所有大小,例如:
import {StyleSheet} from ‘react-native’;
import { Dimensions, Platform, PixelRatio } from ‘react-native’;

const {
    width,
    height
} = Dimensions.get(‘window’);

const scale = width / 320;

const ratioKeys = {
    fontSize: true,
    paddingHorizontal: true,
    paddingVertical: true,
    paddingTop: true,
    paddingLeft: true,
    paddingRight: true,
    paddingBottom: true,
    padding: true,
    marginHorizontal: true,
    marginVertical: true,
    marginTop: true,
    marginRight: true,
    marginLeft: true,
    marginBottom: true,
    margin: true,
    width: true,
    height: true,
    lineHeight: true,
}

// automatically scale specific keys (specified above) according to the screen size
const parseKey = (key, value) => {

   if (ratioKeys[key]) {
        value = value * scale;
    }

   return value;
}

export const parseStyle = (style) => {
    console.log(‘style -> ’, style);
    return Object.keys(style).reduce((output, key) => {
        output[key] = parseKey(key, style[key]);
        return output;
    }, {});
}

const parseStyleSheet = (styles) => {
    console.log(‘styles -> ’, styles);
    return Object.keys(styles).reduce((output, key) => {
       output[key] = parseStyle(styles[key]);
       return output;
    }, {});
}

export default {
    create: (style) => {
        return StyleSheet.create(parseStyleSheet(style));
    }
}

看起来这样做不会自动支持,所以我猜我错过了什么?


它肯定不是开箱即用的支持。 - 10101010
1个回答

0

我看到这个库作为一个解决方案,它支持媒体查询,如果我们觉得需要比 flexbox 更多的自定义,我们可能最终会使用它。我已经看到它在实际应用中的效果,它似乎可以满足你的一些需求:https://github.com/vitalets/react-native-extended-stylesheet


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接