【问题标题】:Responsive grid in React NativeReact Native 中的响应式网格
【发布时间】:2018-01-16 02:39:17
【问题描述】:

我的应用主页由一个导航栏和六个大圆形按钮组成。
我想将按钮放置在纵向 2x3 和横向 3x2 的(响应式)网格中。 视觉上是这样的:

portrait:
+-----------+
|   navbar  |
|           |
| +--+ +--+ |
| |B1| |B2| |
| +--+ +--+ |
| +--+ +--+ |
| |B3| |B4| |
| +--+ +--+ |
| +--+ +--+ |
| |B5| |B6| |
| +--+ +--+ |
+-----------+

landscape:
+-------------------------+
|         navbar          |
|   +--+   +--+   +--+    |
|   |B1|   |B2|   |B3|    |
|   +--+   +--+   +--+    |
|   +--+   +--+   +--+    |
|   |B4|   |B5|   |B6|    |
|   +--+   +--+   +--+    |
+-------------------------+

我目前的解决方案并不令人满意,因为它在改变方向时无法正确调整大小:

纵向(精细):

但是,在横向上:

这是我的组件渲染方法:

const rows = 3;
const cols = 2;
const marginHorizontal = 4;
const marginVertical = 4;
const width = (Dimensions.get('window').width / cols) - (marginHorizontal * (cols + 1));
const height = (Dimensions.get('window').height / rows) - (marginVertical * (rows + 1));

render() {
  return (
  <Container ref="root">
    <ScrollView style={stylesGrid.scrollContainer}>
      <View style={stylesGrid.sectionContainer}>
        <View style={stylesGrid.boxContainer}><Text>B1</Text></View>
        <View style={stylesGrid.boxContainer}><Text>B2</Text></View>
        <View style={stylesGrid.boxContainer}><Text>B3</Text></View>
        <View style={stylesGrid.boxContainer}><Text>B4</Text></View>
        <View style={stylesGrid.boxContainer}><Text>B5</Text></View>
        <View style={stylesGrid.boxContainer}><Text>B6</Text></View>
      </View>
    </ScrollView>
  </Container>
);
}

const stylesGrid = StyleSheet.create({
  scrollContainer: {
    flex: 1,
  },
  sectionContainer: {
    flex: 1,
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'center',
    alignItems: 'center',
  },
  boxContainer: {
    marginTop: marginVertical,
    marginBottom: marginVertical,
    marginLeft: marginHorizontal,
    marginRight: marginHorizontal,
    width: width,
    height: height,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'gold',
  },
});

在横向加载时会发生更糟糕的情况:改变方向时甚至不会保留 3x2 布局...

对 react-native 中一致的响应式布局有什么建议吗?

【问题讨论】:

  • 我认为您需要在方向更改时重新计算样式中的宽度和高度值。滚动容器将不再具有正确的尺寸
  • 谢谢。听从了你的建议。看我的回答。

标签: css react-native flexbox


【解决方案1】:

我按照@agmcleod 的建议解决了:在构造函数中添加了一个方向更改侦听器:

Dimensions.addEventListener('change', () => {
  if (this.refs.root) { // avoid updating state when not necessary
    this.setState({
      orientation: Dimensions.get('window').width < Dimensions.get('window').height ? 'portrait' : 'landscape'
    });
  }
});

然后移动了设置布局变量的逻辑内部 render()函数。

像魅力一样工作。

【讨论】:

    【解决方案2】:

    您应该考虑使用React native Easy Grid。 这是一个强大且易于使用的插件

    【讨论】:

    • 我认为该插件可以解决问题,但我更喜欢自己解决问题,首先... :-) 谢谢。
    猜你喜欢
    • 2015-08-13
    • 2022-11-30
    • 2022-01-14
    • 1970-01-01
    • 2019-03-11
    • 1970-01-01
    • 1970-01-01
    • 2017-07-28
    • 1970-01-01
    相关资源
    最近更新 更多