首页 > 解决方案 > Flex box 不会导致本机反应?

问题描述

我正在使用 flex-box 设计反应原生应用程序的 UI。但是它的代码没有显示预期的结果?

问题

Margin 属性InnerContainer2没有margin:'5%'垂直覆盖相等的空间。

代码:

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

export default class App extends Component {
  render() {
    return (
      <View style={styles.container}>
        <View style={styles.innerContainer1}>
          <View style={styles.innerContainer2}>
            <Text style={styles.welcome}>This is live reload</Text>
          </View>
        </View>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'grey'
  },
  innerContainer1: {
    flex: 1,
    width: '80%',
    margin: '10%',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'lightgrey'
  },
  innerContainer2: {
    flex: 1,
    width: '80%',
    margin: '5%',
    height: 'auto',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'grey'
  },
  welcome: {
    textAlign: 'center',
    margin: 10,
  }
});

预期产出

在此处输入图像描述

实际输出

在此处输入图像描述

标签: react-nativereact-native-flexbox

解决方案


好的,有两件事:

1) Margin/Padding 不能很好地与“百分比值”配合使用,因为它会干扰其他组件的高度和宽度。因此,请始终使用确切的值。如果您担心其他屏幕尺寸,那么您可以使用尺寸库来计算任何屏幕的确切宽度和高度,并从那里分配一个边距。

2) 当您必须为父元素内的两个组件分配比率时,通常使用 Flex。此示例将使子组件占其父元素的 50%。

例如:

父组件 => flex: 1

子(A)组件 => 弹性:0.5

子(B)组件 => 弹性:0.5

除了我对你的风格类做了一些调整。它按预期工作。希望你能理解或者你可以问我:)

  const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'grey',
  },
  innerContainer1: {
    // flex: 1, used when you have to assign a ratio for two components inside a parent element
    width: '80%',
    height: '80%',
    margin: 10,
    justifyContent: 'center',
    //  alignItems: 'center',      It gives the desired result when used in the parent component.
    backgroundColor: 'lightgrey',
  },
  innerContainer2: {
    // flex: 1, used when you have to assign a ratio for two components inside a parent element.
    width: '80%',
    margin: 30,
    height: '80%',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'red',
  },
  welcome: {
    textAlign: 'center',
    margin: 10,
  },
});

参考:

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

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


推荐阅读