React Native 的响应式屏幕

问题描述 投票:0回答:4

如何用 React Native 编写样式表,使应用程序能够在 iOS 和 Android 平台上的所有设备上同等扩展?我尝试使用react-native-responsive-screen包,但没有一个包真正有助于正确缩放应用程序,特别是在使用边距和填充对齐内容时。关于如何克服这个问题有什么建议吗?

javascript react-native responsive-design
4个回答
2
投票

除了使用弹性布局系统之外,到目前为止我所做的是编写一个缩放函数,它可以使边距和字体大小适应不同的屏幕尺寸。

垂直边距示例:

const HEIGHT_SCALE = 667; // this is the standard iphone 7 height, but you can use a different height as your standard height. 
const scaleMargins = (margin) => {
    const ratio = margin / HEIGHT_SCALE; 
    const newScale = Math.round(ratio * SCREEN_WIDTH);
    return newScale; 
}

const MARGIN_15 = scaleMargins(15);

使用示例:

<Text style={{ marginTop: MARGIN_15, marginBottom: MARGIN_15 }}>
Your Text with adaptive margins goes here
</Text>

优点

您还可以调整

scaleMargins
功能以获得响应式字体大小或水平边距/填充。因此只需使用不同的缩放因子。对于水平边距,您可以使用此缩放功能:

const WIDTH_SCALE = 375; // Standard iphone 7 screen width. You can get it from Dimension.get('screen').width 
const scaleVerticalMargins = (margin) => {
    const ratio = margin / WIDTH_SCALE; 
    const newScale = Math.round(ratio * SCREEN_WIDTH);
    return newScale; 
}

另一个优点:您可以创建一个全局样式类,在其中为整个应用程序计算一次所有必要的边距等。


1
投票

首先,您应该了解flexbox,然后使您的组件在所有设备上完美可见。

在这个过程中,一些图书馆可以帮助你。

react-native-lightweight-responsive 就是这么简单。

import Responsive from 'react-native-lightweight-responsive';

<View style={{
  width: Responsive.width(300),
  height: Reponsive.width(300),
}}/>

上面的代码将使您的组件在所有设备上都相同可见。


0
投票

您必须在样式中使用 flex 属性,这将帮助我们的视图根据屏幕宽度和高度进行相应调整。


0
投票

我很高兴分享我最新的 npm 包,@harshitkishor/rn-responsive,它是为寻求简化制作响应式布局的 React Native 开发人员量身定制的。 📱💻

yarn add @harshitkishor/rn-responsive

探索本文中的详细用法和示例 - 官方文章

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.