【问题标题】:Maintain view's flex layout with text content使用文本内容维护视图的弹性布局
【发布时间】:2016-11-19 11:39:40
【问题描述】:

我希望视图占屏幕的三分之一(水平),因此我创建了 3 个视图,并在每个视图上设置了 flex: 1

现在如果我在里面放一个<Text>,它会比另外两个稍大。

如何保持它占屏幕的三分之一?

这里有一些代码:

import React, { Component } from 'react';
import { AppRegistry, Text, View } from 'react-native';

class FlexDirectionBasics extends Component {
  render() {
    return (
      <View style={{flex: 1, flexDirection: 'row'}}>
        <View style={{flex: 1, backgroundColor: 'powderblue'}}>
          <Text style={{backgroundColor: 'red'}}>text</Text>
        </View>
        <View style={{flex: 1, backgroundColor: 'skyblue'}} />
        <View style={{flex: 1, backgroundColor: 'steelblue'}} />
      </View>
    );
  }
};

AppRegistry.registerComponent('AwesomeProject', () => FlexDirectionBasics);

图片:

【问题讨论】:

    标签: react-native flexbox


    【解决方案1】:

    每个组件的flex:1 意味着它占用了整个空间。试试这个:

    <View style={{flex: 1, flexDirection: 'row'}}>
        <View style={{flex: 0.33, backgroundColor: 'powderblue'}}>
          <Text style={{backgroundColor: 'red'}}>text</Text>
        </View>
        <View style={{flex: 0.33, backgroundColor: 'skyblue'}} />
        <View style={{flex: 0.33, backgroundColor: 'steelblue'}} />
      </View>
    

    【讨论】:

    • 这不是真的,当您为每个组件设置flex: 1 时,它们会按比例分配。尝试将第一个示例中的width: 50, height: 50 更改为flex: 1 facebook.github.io/react-native/docs/flexbox.html。您是否尝试过您的解决方案?
    • 但是您的视图中没有任何内容可以显示,所以我猜 flexbox 会将其扩展到整个宽度。我没有在水平视图上尝试过。它适用于垂直父视图。我会检查一下并通知您。
    【解决方案2】:

    使用相同的代码时,我看不出有什么不同。附上屏幕截图供您参考。每个块的宽度为 188.

    【讨论】:

    • 不知道该告诉你什么,我只是添加了一张我所看到的图片。我确实想出了如何解决它,为所有组件添加相同的宽度(除了flex: 1
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-08
    • 1970-01-01
    • 2013-05-03
    • 1970-01-01
    • 2020-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多