首页 文章

React-Native:当alignItems设置为'center'时,宽度不会从partent视图继承

提问于
浏览
0

我再次使用React-Native,这次专注于布局,并遇到了一个有趣的问题 . 如果我在父视图上设置alignItems:'center',则其下的子节点似乎没有正确设置其宽度 .

此代码将生成一个占据整个屏幕的绿色框 .

React.createClass({
  render: function() {
    return (
      <View style={{flex: 1, alignItems: 'center',backgroundColor:'green'}}>
        <View style={{flex:1, backgroundColor:'blue'}} />      
        <View style={{flex:1, backgroundColor:'red'}} />
      </View>
    );
  }
});

但是,如果我删除了alignItems样式或将其设置为'stretch',我会在红色框顶部出现一个蓝色框,正如我所料

var BrownBag = React.createClass({
  render: function() {
    return (
      <View style={{flex: 1, backgroundColor:'green'}}>
        <View style={{flex:1, backgroundColor:'blue'}} />      
        <View style={{flex:1, backgroundColor:'red'}} />
      </View>
    );
  }
});

在理解alignItems如何工作时,我缺少什么?

1 回答

  • 2

    问题是,当您添加 alignItems: 'center' 时,内部项目变为零宽度,因此它们会自行折叠 . 您可以通过向子视图添加一些宽度来自己看到这个...

    <View style={{flex: 1, backgroundColor:'green', alignItems: 'center'}}>
          <View style={{flex:1, backgroundColor:'blue', width: 300}} />      
          <View style={{flex:1, backgroundColor:'red', width: 300}} />
        </View>
    

相关问题