React-Native:带有百分比值的保证金

Tho*_*upo 7 css flexbox reactjs react-native 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'
    }
});
Run Code Online (Sandbox Code Playgroud)

非常感谢你 !

小智 9

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

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

    使用尺寸来计算以获取屏幕的高度和宽度。

    var {height, width} = Dimensions.get('window');
    
    Run Code Online (Sandbox Code Playgroud)

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

    示例示例:

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