使用React Native的样式表setStyleAttributePreprocessor方法的示例?

时间:2018-02-28 13:36:44

标签: reactjs react-native

我们注意到StyleSheet有一个名为 setStyleAttributePreprocessor method

  

设置用于预处理样式属性值的函数。这在内部用于处理颜色和变换值。你不应该使用它,除非你真的知道自己在做什么,并且已经用尽其他选择。

我想知道是否有使用的例子。基本上我们希望根据整个应用程序的屏幕大小来缩放宽度和高度:

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

const widthScale = width / 320;
const heightScale = height / 568;

1 个答案:

答案 0 :(得分:1)

结束这样做:

import {StyleSheet} from 'react-native';
import {Dimensions} from 'react-native';

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

const widthScale = width / 320;
const heightScale = height / 568;

const widthRatioKeys = {
    fontSize: true,
    paddingHorizontal: true,
    paddingLeft: true,
    paddingRight: true,
    padding: true,
    marginHorizontal: true,
    marginRight: true,
    marginLeft: true,
    margin: true,
    borderRadius: true,
    borderWidth: true,
    right: true,
    left: true,
}

const heightRatioKeys = {
    paddingVertical: true,
    paddingTop: true,
    paddingBottom: true,
    marginVertical: true,
    marginTop: true,
    marginBottom: true,
    height: true,
    minHeight: true,
    lineHeight: true,
    top: true,
    bottom: true,
}


Object.keys(widthRatioKeys).forEach(key => {
    StyleSheet.setStyleAttributePreprocessor(key, (value) => {
        return value * widthScale;
    });
});

Object.keys(heightRatioKeys).forEach(key => {
    StyleSheet.setStyleAttributePreprocessor(key, (value) => {
        return value * heightScale;
    });
});