如何使视图与顶部和底部以及左侧和右侧对齐?

时间:2019-02-13 07:01:22

标签: react-native user-interface layout flexbox

我正在尝试创建ui设计,这是我当前的设计:

screenshot

在这里,我有两个矩形视图,这是我的代码:

  <View style={{ flexDirection: 'column', alignContent: 'space-between' }}>
                <View style={{ flexDirection: 'row' }}>
                    <View style={{ width: 100 * 2, height: 100, backgroundColor: 'red'}}/>
                </View>
                <View style={{ flexDirection: 'row', justifyContent: 'flex-end' }}>
                    <View style={{ width: 100 * 2, height: 100, backgroundColor: 'red'}}/>
                </View>
            </View>

预期的输出是第一个矩形应该在左上方(通过下面的图像看起来正确),第二个矩形应该在右下方。但是它位于第一个矩形旁边。

如何移动矩形到右下角?我尝试了所有操作,例如证明内容,使用flex结束但没有任何更改。请帮助

3 个答案:

答案 0 :(得分:0)

使用Dimensions将为您解决问题。 如下修改您的代码

    import React, { Component } from 'react';
import { AppRegistry, View , Dimensions} from 'react-native';
const width = Dimensions.get('window').width

export default class FlexDirectionBasics extends Component {
  render() {
    return (
      // Try setting `flexDirection` to `column`.
      <View style={{ flex:1,flexDirection: 'column', alignContent: 'space-between' }}>
                <View style={{ flex: 1,flexDirection: 'row' }}>
                    <View style={{ width: width/2, height: 100, backgroundColor: 'red'}}/>
                </View>
                <View style={{flexDirection: 'row' , justifyContent: 'flex-end'}}>
                    <View style={{ width: width/2 ,  height:100 ,backgroundColor: 'red'}}/>
                </View>
            </View>
    );
  }
};

// skip this line if using Create React Native App
AppRegistry.registerComponent('AwesomeProject', () => FlexDirectionBasics);

输出:enter image description here

答案 1 :(得分:0)

    <View style={{ flexDirection: 'column', justifyContent: 'space-between', flex: 1 }}>
      <View style={{ flexDirection: 'row' }}>
          <View style={{ width: 100 * 2, height: 100, backgroundColor: 'red'}}/>
      </View>
      <View style={{ flexDirection: 'row', justifyContent: 'flex-end' }}>
          <View style={{ width: 100 * 2, height: 100, backgroundColor: 'red'}}/>
      </View>
    </View>

首先,您必须设置flex: 1,以便它可以增长。第二步是添加justifyContent: 'space-between'而不是alignContent: 'space-between'

答案 2 :(得分:0)

您需要将flex:1属性添加到父样式。 该属性也称为justifyContent而不是alignContent

这是您的代码已更正

<View style={{  flex:1, flexDirection: 'column', justifyContent: 'space-between' }}>
            <View style={{ flexDirection: 'row' }}>
                <View style={{ width: 100 * 2, height: 100, backgroundColor: 'red'}}/>
            </View>
            <View style={{ flexDirection: 'row', justifyContent: 'flex-end' }}>
                <View style={{ width: 100 * 2, height: 100, backgroundColor: 'red'}}/>
            </View>
        </View>

您可以在此处查看示例:https://snack.expo.io/@clemband/funny-cereal