对齐项目 flex 端反应原生

Vam*_*anu 6 css flexbox react-native

我是 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 ? 
        }
     });
Run Code Online (Sandbox Code Playgroud)

Joh*_*ner 9

这将在 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>
Run Code Online (Sandbox Code Playgroud)


LGS*_*Son 8

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

为了使这项工作,你需要display: flexcontainer:,一套flex: 1;textStyle:这将使其采取一切可用的空间,并推iconStyle:到最右边。

如果margin-left: auto可用(在 上iconStyle:),则无需 即可flex: 1,尽管您仍然需要display: flexcontainer:

而且应该display: flexmain_container:过,除非是自动加入其他地方(同样适用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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

  • 这是 React Native 还是 HTML?或者这些概念适用于两者? (2认同)