css - React-Native:带百分比值的边距

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

我正在尝试在我的 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'
    }
});

非常感谢!

最佳答案

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

设置组件尺寸的最简单方法是为样式添加固定的宽度和高度。 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
    

关于css - React-Native:带百分比值的边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50485622/

相关文章:

javascript - 在页面加载时隐藏 DIV

html - 并排堆叠 div

javascript - 使用 jQuery Masonry 时如何使 block 居中

javascript - 我应该在 redux 应用程序中嵌套 immutable.js Map 和 List 吗?

javascript - 过滤器 JSON 不起作用

typescript - 在 native react 中创建下拉菜单

javascript - 如何显示当前的获取 url 以及我的状态发生了什么?

css - 如何在 Foundation 5 中创建适用于所有媒体查询的自定义网格?

javascript - 无法解析子组件中的 props

react native useState 错误 ("is read-only")