React-Native:当alignItems设置为“center"时,宽度不会从partent视图继承 [英] React-Native: Width not inherited from partent view when alignItems is set to 'center'

查看:57
本文介绍了React-Native:当alignItems设置为“center"时,宽度不会从partent视图继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我又在玩 React-Native,这次专注于布局,遇到了一个有趣的问题.如果我在父视图上设置 alignItems:'center',它下面的子视图似乎没有正确设置它们的宽度.

I am playing around with React-Native again, focusing on layouts this time around, and ran into an interesting problem. If I set alignItems:'center' on a parent View, the children under it don't seem to have their widths properly set.

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

This code will produce a single green box taking up the whole screen.

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 样式或将其设置为拉伸",我会像预期的那样在红色框的顶部看到一个蓝色框

However if I remove the alignItems style or set it to 'stretch' I get a blue box on top of a red box as I would expect

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

What am I missing in my understanding of how alignItems works?

推荐答案

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

The problem is that when you add alignItems: 'center' the internal items become zero width, so they collapse in on themselves. You can see this yourself by adding some width to the sub-views like so...

    <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>

这篇关于React-Native:当alignItems设置为“center"时,宽度不会从partent视图继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆