首页 > 解决方案 > 在 React Native 中使用 flex 进行网格布局

问题描述

我正在使用 flex 来显示一些配置文件。

<View style={styles.flexContainer}>
    <View style={styles.profileImgContainer}  >
        <Image style={styles.profileImg}/>
    </View>
    <View style={styles.name}>
      <Markdown>{user.name}</Markdown>
    </View>
</View>

const styles = StyleSheet.create({
  flexContainer: {
    flexDirection: 'row'
  },
  ...,
});

我想使用 row1 和 row2 将 Image 放在 col1 的中心。我想将 Markdown 放在 row1 的 col2 中。

我的 flex 容器应该是这样的。

    col1 | col2 |
row1     |______|
         |      |
row2 ____|______|

我怎么能做到这一点?

标签: react-native

解决方案


输出:

输出

代码:

<View style={styles.container}>
  <View style={{flex: 1, flexDirection: 'row'}}>
    <View style={styles.col1}>
      <Image source={{uri: 'https://www.deine-tierwelt.de/magazin/wp-content/uploads/sites/2/2013/10/Australian-Cattle-Dog-1000x570.jpg'}} style={{width: 100, height: 100}} />
    </View>
    <View style={styles.col2}>
      <View style={styles.row1}>
          <Text> Username </Text>
      </View>
      <View style={styles.row2}>

      </View>
    </View>
  </View>
  <View style={{flex: 1}} />
</View>

样式表:

container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    flexDirection: 'column',
    padding: 8,
  },
  col1: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'gray'
  },
  col2: {
    flex:1,
    flexDirection: 'column'
  },
  row1: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    backgroundColor: 'lightgray'
  },
  row2: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    backgroundColor: 'darkgray'
  }

演示:

https://snack.expo.io/eoENHOHvq


推荐阅读