【问题标题】:Align Items flex end react native对齐项目 flex 端反应原生
【发布时间】:2017-06-06 13:56:27
【问题描述】:

我是 flexbox 样式的新手。我在尝试将 flexbox 中的元素对齐到最右角时遇到问题。我编写了以下代码将图像中的加号对齐到红色框的右上角,但它没有按预期工作。请帮我解决这个问题。

    <View style={main_container}>
      <ScrollView>
          <TouchableHighlight>
                <View style={container}> 
                    <Image style={imageStyle} source={{uri: this.props.data.picture}} />
                    <Text style={textStyle}> {this.props.data.company} </Text>                  
                    <Text style={iconStyle}> 
                        <Icon name={'plus-circle'} size={20} color={'#003057'} />
                    </Text>
                </View>
            </TouchableHighlight>
      </ScrollView>
      <Footer />
     </View>

     const styles = StyleSheet.create({
        main_container: {
           flex: 1,
           flexDirection: 'column',
           marginTop: 70
         },
         container: {
           flex: 1,
           flexDirection: 'row',
           alignItems: 'center',
           margin: 6,
           backgroundColor: 'red'
         },
         imageStyle: {
           width: 50,
           height: 50
         },
        textStyle: {
           fontSize: 10
        },
        iconStyle: {
           backgroundColor: 'yellow',
           alignSelf: 'flex-end'   //why is it aligning the image vertically ? 
        }
     });

【问题讨论】:

  • margin-left: auto - 这会将它推到右边
  • 嘿@pol,react native 没有 marginLeft: auto,我想知道 alignSelf: 'flex-end' 有什么问题。
  • margin-left: "auto" 工作不要忘记 ""

标签: css react-native flexbox


【解决方案1】:

flex-end 工作交叉轴并将图标垂直推到末尾(其父级的底部),您可以在代码中看到它没有像文本和图像一样居中。

要完成这项工作,您需要在container: 上设置display: flex,在textStyle: 上设置flex: 1;,这将占用所有可用空间并将iconStyle: 推到最右边。

如果margin-left: auto 可用(在iconStyle: 上),那么没有flex: 1 也可以,但您仍然需要container: 上的display: flex

main_container: 上也应该有 display: flex,除非它自动添加到其他地方(container: 也是如此)

示例 sn-p

div {
  display: flex;
  align-items: center;
  background: lightgray;
  height: 50px;
  margin-bottom: 5px
}
span {
  padding: 5px;
}

div.nr1 span:nth-child(2) {
  flex: 1;
}

div.nr2 span:nth-child(3) {
  margin-left: auto;
}
<div class="nr1">
  <span>image</span>
  <span>text</span>
  <span>icon</span>
</div>

<div class="nr2">
  <span>image</span>
  <span>text</span>
  <span>icon</span>
</div>

【讨论】:

  • 这是 React Native 还是 HTML?或者这些概念适用于两者?
  • @HendyIrawan 这个示例展示了 HTML 和 Flexbox,尽管 alignSelf 的概念是相同的,并且示例 nr1 中的flex: 1; 对两者都适用
【解决方案2】:

这将在 react-native 中完成,以使所有内容正确排列在 y 轴上。关键是中心元素上的flex:1

<View style={{flexDirection: 'row', alignItems: 'center'}}> 
  <Image source={{uri: this.props.data.picture}} />
  <Text style={{flex:1}}>{this.props.data.company}</Text>                  
  <Icon name={'plus-circle'} size={20} color={'#003057'} />
</View>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-24
    • 1970-01-01
    • 2011-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多