最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React Native: Why don't flex justifyContent and alignItems work for child <View>? - Stack Ove

programmeradmin5浏览0评论

In React Native, I have a child view inside another view, but it doesn't center in the middle of the page. But if the child view is not inside the parent view and alone, it centers fine in the middle of page.

How can I make it so that the child view centers to the middle of the page while being inside another view (parentView)?

Here is the code:

  render() {

    return (
      <View id="parentView">
          <View
            id="childView" 
            style={
               flex: 1,
               justifyContent: 'center',
               alignItems: 'center',
            }
          >
            <Text>Center This to Middle of Page</Text>
          </View>
          <View
            id="childViewTwo" 
          >
            <Text>Don't center me</Text>
          </View>
      </View>
    );
  }

In React Native, I have a child view inside another view, but it doesn't center in the middle of the page. But if the child view is not inside the parent view and alone, it centers fine in the middle of page.

How can I make it so that the child view centers to the middle of the page while being inside another view (parentView)?

Here is the code:

  render() {

    return (
      <View id="parentView">
          <View
            id="childView" 
            style={
               flex: 1,
               justifyContent: 'center',
               alignItems: 'center',
            }
          >
            <Text>Center This to Middle of Page</Text>
          </View>
          <View
            id="childViewTwo" 
          >
            <Text>Don't center me</Text>
          </View>
      </View>
    );
  }
Share Improve this question edited Sep 9, 2016 at 0:41 asked Sep 8, 2016 at 23:18 user3259472user3259472 0
Add a ment  | 

1 Answer 1

Reset to default 6

Just add flex:1 to your parent View. I made a working example for you: https://rnplay/apps/zHO1YA

return (
       <View id="parentView" style={{flex: 1}}>
          <View
            id="childView" 
            style={{
               flex: 1,
               justifyContent: 'center',
               alignItems: 'center',
            }}
          >
            <Text>Center This to Middle of Page</Text>
          </View>
          <View
            id="childViewTwo" 
          >
            <Text>Don't center me</Text>
          </View>
      </View>
    );
发布评论

评论列表(0)

  1. 暂无评论