有没有办法在 react-native 中缩放视图?

IT技术 javascript ios reactjs react-native
2021-05-24 17:19:17

我有一个View带有一些组件的 react-native。虽然一切都在 iPhone 6 和 5 上正确显示,但在 iPhone 4s 上查看时,其中一个组件的底部被稍微切掉了。

我看到有一些方法可以缩放 base64 图标。有什么方法可以将整个容器视图缩放为均匀地变小或变大?

2个回答

你的问题可以分为两部分:

1, 缩放width, height,paddingsmargins这些可以通过使用%轻松实现aspectRatio

2、要缩放Text,您可能需要考虑使用Extended StyleSheet,它允许您使用rem.

您可以简单地按照教程“为所有屏幕尺寸开发 React Native UI 的 7 个技巧”了解如何使用上述技巧。

此外,请查看Extended StyleSheet Scaling,它允许使用$scale变量根据条件进行缩放。

这样的事情对你有帮助吗?

你的样式表.js

import {StyleSheet} from 'react-native';
var Dimensions = require('Dimensions');
var {width, height} = Dimensions.get('window');


export function create(styles: Object): {[name: string]: number} {
  const platformStyles = {};
  Object.keys(styles).forEach((name) => {
    let {sm,md,lg, ...style} = {...styles[name]};
    // iphone 4s and older
    if(sm && width < 375){

      style = {...style, ...sm};
    }
    // iphone 5,5s
    if(md && width >= 375 && width <414){

      style = {...style, ...md};
    }
    // iphone 6 and bigger
    if(lg && width >= 414){

      style = {...style, ...lg};
    }


    platformStyles[name] = style;
  });
  return StyleSheet.create(platformStyles);
}

然后在您的风格中,您可以在不同的屏幕尺寸上指定组件的大小,如下所示

import YourStyleSheet from './path/YourStyleShett'    
const styles = YourStyleSheet.create({
      component:{
        sm:{fontSize: 20,},
        md:{fontSize: 30,},
        lg:{fontSize: 30,},
        textAlign: 'center',
        marginBottom: 10,
        fontWeight:'bold',
        color:colors.white,
      }
    });