居中项目,然后左侧有一个项目 - Flexbox React Native

时间:2016-01-12 21:01:01

标签: flexbox react-native

在React Native中使用flexbox我在尝试执行以下看似简单的任务时遇到了很多麻烦:

我在容器中有两个项目。我希望一个居中,另一个直接躺在它的左边。

1 个答案:

答案 0 :(得分:7)

您可以更改两个外部组件的弹性大小属性,只要它们相同,中间项将居中。

注意第一个组件的justifyContent:'flex-end'属性。这种造型使物品直接位于中间物品的左侧。

  <View style={styles.container}>
    <View style={styles.component1}>
        <Text>Right</Text>
    </View>
    <View style={styles.component2}>
        <Text style={{ textAlign:'center' }}>I am the Center Component</Text>  
    </View>
    <View style={styles.component3}></View>
  </View>

  container: {
    flexDirection:'row',
    flex:1,
    marginTop:60
  },
  component1: {
    flex:1,
    flexDirection: 'row',
    justifyContent: 'flex-end',
    height:80
  },
  component2: {
    flex:1,
    height:80,
    backgroundColor: 'red',
    justifyContent:'center'
  },
  component3: {
    flex:1,
  }

此外,整个代码如下:

'use strict';

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
} = React;

var SampleApp = React.createClass({
  render: function() {
    return (
      <View style={styles.container}>
        <View style={styles.component1}>
                    <Text>Right</Text>
        </View>
        <View style={styles.component2}>
            <Text style={{ textAlign:'center' }}>I am the Center Component</Text>  
        </View>
        <View style={styles.component3}></View>
      </View>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    flexDirection:'row',
    flex:1,
    marginTop:60
  },
  component1: {
    flex:1,
    flexDirection: 'row',
    justifyContent: 'flex-end',
    height:80
  },
  component2: {
    flex:1,
    height:80,
    backgroundColor: 'red',
    justifyContent:'center'
  },
  component3: {
    flex:1,
  }
});

AppRegistry.registerComponent('SampleApp', () => SampleApp);