排列项目flex-end React Native

9
我对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 ? 
        }
     });

3
margin-left: auto - 这会将它向右推。 - pol
嘿@pol,React Native没有marginLeft:auto,我想知道alignSelf:'flex-end'有什么问题。 - Vamshi Kolanu
margin-left: "auto" 可以工作,不要忘记 ""。 - Mahir
2个回答

11

这将在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>

10

flex-end 属性在交叉轴上起作用,将图标垂直推到父元素的底部,你可以在你的代码中看到,它没有像文本和图片一样居中。

要使其生效,您需要在container:上设置display: flex,在textStyle:上设置 flex: 1;,这将使其占据所有可用空间并将iconStyle: 推到最右边。

如果iconStyle:上有margin-left: auto,那么它就不需要flex: 1,但是您仍然需要在container:上设置display: flex

还应该在main_container:上设置display: flex,除非其他地方已自动添加(container:也是如此)

示例片段:

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>


3
这是React Native还是HTML?或者这些概念都适用于两者? - Hendy Irawan
1
@HendyIrawan 这个示例展示了HTML和Flexbox,虽然alignSelf的概念是相同的,并且在示例_nr1_中flex: 1;适用于两者。 - Asons

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接