【问题标题】:React-Native: Margin with percentage valueReact-Native:百分比值的保证金
【发布时间】:2018-11-02 06:44:40
【问题描述】:

我正在尝试在我的 React Native 项目中为边距样式属性使用百分比值,但它似乎降低了我的 View 组件之一的高度。如果我用绝对值替换百分比值,则没有更多问题并且可以正常工作。您是否尝试在 React Native 中使用百分比值作为边距?以下是重现此问题的一些代码示例:

import React, { Component } from 'react';
import { Text, View, StyleSheet } from 'react-native';

export default class App extends Component {
  render() {
    return (
      <View style={styles.scene}>
        <View style={styles.card}>
          <View style={styles.container}>
            <Text>Hello World</Text>
          </View>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
    scene: {
        backgroundColor: '#F9E8D5',
        flex: 1,
        justifyContent: 'flex-start',
        alignItems: 'center',
        flexDirection: 'column'
    },
    card: {
        backgroundColor: '#E6D5C3',
        flex: 0.2,
        flexDirection: 'column',
        marginTop: '20%' // Replace by 20
    },
    container: {
        backgroundColor: '#FFFFFF',
        flex: 1,
        flexDirection: 'column',
        justifyContent: 'center'
    }
});

非常感谢!

【问题讨论】:

  • 当您使用百分比时,它适用于您正在工作的“框”(而不是屏幕高度)。在您的代码中,您将获得 backgroundColor="#e6d5c3" 框的 20%
  • @gaback 不,这不是真的 marginTop: '20%' 是“包含框高度的 20%,即场景”。填充很好,问题是为什么它弄乱了“容器”视图的高度(在 android 和 Ios 上,但不在网络上)

标签: css reactjs react-native flexbox react-native-flexbox


【解决方案1】:

组件的高度和宽度决定了它在屏幕上的大小。

设置组件尺寸的最简单方法是为样式添加固定的宽度和高度。 React Native 中的所有维度都是无单位的,并且表示与密度无关的像素。

以这种方式设置尺寸对于应该始终以完全相同的尺寸呈现的组件来说很常见,无论屏幕尺寸如何。

在组件样式中使用 flex 可让组件根据可用空间动态扩展和收缩。通常你会使用 flex: 1。

以下参考将用于样式

  1. https://facebook.github.io/react-native/docs/height-and-width.html

  2. https://medium.com/the-react-native-log/tips-for-styling-your-react-native-apps-3f61608655eb

  3. https://facebook.github.io/react-native/docs/layout-props.html#paddingtop

    使用Dimensions计算得到屏幕的高度和宽度。

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

    通过获取屏幕大小指定百分比并将其转换为百分比。

    示例:

    const { height } = Dimensions.get('window');
    
    paddingTop: height * 0.1 // 10 percentage of the screen height
    

【讨论】:

  • 得到这样的高度let _height = Dimensions.get('window').height;
  • 它没有回答这个问题。它只是提供了一种使用 Dimensions.get("window") 的解决方法,在 React Native 文档中明确建议不要这样做: 注意:虽然尺寸可以立即使用,但它们可能会改变(例如由于设备旋转),因此任何渲染逻辑或样式依赖在这些常量上应该尝试在每次渲染时调用这个函数,而不是缓存值(例如,使用内联样式而不是在 StyleSheet 中设置值)。
【解决方案2】:

这是一个真正的错误,但 Facebook 不在乎。

https://github.com/facebook/react-native/issues/19164

【讨论】:

    猜你喜欢
    • 2011-04-23
    • 2022-01-24
    • 2013-10-29
    • 1970-01-01
    • 2013-10-30
    • 2022-10-15
    • 2016-04-14
    • 1970-01-01
    • 2014-07-29
    相关资源
    最近更新 更多