【问题标题】:React-Native: Width not inherited from partent view when alignItems is set to 'center'React-Native:当 alignItems 设置为“中心”时,宽度不会从父视图继承
【发布时间】:2016-02-18 06:48:52
【问题描述】:

我又在玩 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 样式或将其设置为“拉伸”,我会得到一个红色框顶部的蓝色框,正如我所期望的那样

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 工作原理的理解缺少什么?

【问题讨论】:

    标签: react-native


    【解决方案1】:

    问题在于,当您添加 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>
    

    【讨论】:

    • 啊,确实有道理!如果不给它视图需要的最小宽度并且没有设置该值,就不能居中,0 就是它。我有点惊讶,因为实际上我试图用弹性尺寸的图像填充红色框。但是对于宽度为 0 的父视图,内部图像的 flex 大小也将为零。谢谢!
    猜你喜欢
    • 2018-06-23
    • 2016-02-29
    • 2021-09-03
    • 2021-05-13
    • 1970-01-01
    • 1970-01-01
    • 2020-09-02
    • 2018-01-15
    • 2013-09-12
    相关资源
    最近更新 更多