【问题标题】:Style width using flex in React Native在 React Native 中使用 flex 的样式宽度
【发布时间】:2015-09-22 15:49:45
【问题描述】:

我正在使用 react native 并尝试设置组件的样式。我有一个包含两个视图(A 和 B)的视图(黑色边框)。我想要看起来像这样的东西 - 我包裹 A 的视图的宽度约为 75%,包裹 B 的视图的宽度约为 25%。

然而,当这个组件被渲染为一个列表时,我得到的是这样的东西——A 视图的宽度取决于它包含多少文本。

我能够将宽度设置为特定数量,但它似乎总是根据我测试它的设备而变化(在 iPhone 5、6、6 plus 上有所不同)。因此,我尝试使用 flex 样式,但似乎无法正确使用。这是我的样式和组件结构的代码:

const styles = StyleSheet.create({
  title: {
    color: '#000',
    textAlign: 'left',
    fontSize: 80,
  },
  row: {
    flex: 1,
    flexDirection: 'row',
    padding: 0,
    height: 180,
    borderBottomColor: '#888',
    borderBottomWidth: 1,
    alignItems: 'stretch'
  },
  innerContainer: {
    flex: 1,
    padding: 0,
    flexDirection: 'row',
    alignItems: 'stretch',
  },
  sideDivider: {
    flex: 0.8,
    padding: 0,
    backgroundColor: '#cacaca',
    justifyContent: 'center'
  },
  sideDividerArrow: {
    flex: 0.2,
    padding: 0,
    alignItems: 'center',
    backgroundColor: 'cyan',
    justifyContent: 'center',
  },
});

...

render() {
    return (
      <View style={styles.row} ref={component => this._root = component}>
        <TouchableHighlight onPress={this.handleClick.bind(this)}>
          <View style={styles.innerContainer}>
            <View style={styles.sideDivider}>
              <Text style={styles.title}>
                  {this.state.routeData.busNumber}
              </Text>
              <Text>{this.state.routeData.fullRoute}</Text>
            </View>
            <View style={styles.sideDividerArrow}>
              <Text>></Text>
            </View>  
          </View>
        </TouchableHighlight>
      </View>
    )
  }
}

感谢任何和所有帮助。谢谢!!

【问题讨论】:

    标签: react-native


    【解决方案1】:

    flex 属性需要一个整数。我们不能使用分数。

    我想渲染以下内容将帮助您获得所需的外观。然后,您可以添加交互并清理内联样式

    <View style ={{flexDirection:'row',flex:1,borderColor:'black',borderWidth:1}}>
      <View style ={{flex:3,backgroundColor:'blue',alignItems:'center',justifyContent:'center'}}>
        <Text>A</Text>
      </View>
      <View style ={{flex:1,backgroundColor:'yellow',alignItems:'center',justifyContent:'center'}}>
        <Text>B</Text>
      </View>
    </View>
    

    【讨论】:

    【解决方案2】:

    您的图片有 3 个组件,但代码实际上有更多。 如果您这样做,代码应该按预期工作:
    - row: flex: 1(确保行是全宽)+ flexDirection: 'row'(所以行子级将从左到右)。
    - 一个容器:flex:3。
    - B 容器:弹性:1。
    A 或 B 的至少一个孩子应该有一个 flex: 1 (或任何其他数字),以确保孩子也伸展以填充父母。

    在您的情况下,给标题和文本组件一个 flex: 1 属性可能会解决问题。
    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2021-02-06
      • 1970-01-01
      • 1970-01-01
      • 2010-12-15
      • 1970-01-01
      • 2022-11-03
      • 1970-01-01
      • 2018-05-09
      • 2021-12-16
      相关资源
      最近更新 更多