React native flexbox - 如何进行百分比调整|| 列|| 响应|| 网格等

Ale*_*rst 11 javascript css flexbox reactjs react-native

在过去几周使用iOS本地反应之后,我似乎遇到了一些flex样式的缺点......特别是在涉及"响应"行为时.

例如,假设您要创建一个包含卡片的视图(这些卡片的元数据来自API).您希望卡片的视图宽度的50%减去边距和填充,并在每个2之后换行.

在此输入图像描述

我对此视图的当前实现将返回的数组拆分为包含2个项的行.列表容器有flex: 1, flexDirection: 'column,行有flex: 1,然后每张卡有flex: 1.最终结果是每行有2列,均匀占据视图宽度的一半.

看起来在React Native样式中没有简单的方法可以做到这一点,而不使用javascript对数据进行某种预处理,以便正确地进行样式设置.有没有人有什么建议?

jev*_*lio 20

使用flexbox可能有更好的方法来实现这一点,但我通常会定义"百分比"帮助器vw以及vh视口宽度和视口高度,以CSS视口大小度量单位命名:

import {Dimensions} from 'react-native';

function vw(percentageWidth) {
  return Dimensions.get('window').width * (percentageWidth / 100);
}

function vh(percentageHeight) {
  return Dimensions.get('window').height * (percentageHeight / 100);
}
Run Code Online (Sandbox Code Playgroud)

要在网格中流动项目,您可以计算项目的适当大小,计算边距和视口大小:

const COLUMNS = 3;
const MARGIN = vw(1);
const SPACING = (COLUMNS + 1) / COLUMNS * MARGIN;

const grid = {
  flex: 1,
  flexWrap: 'wrap',
  flexDirection: 'row',
  justifyContent: 'flex-start'
};

const cell = {
  marginLeft: MARGIN,
  marginTop: MARGIN,
  width: vw(100) / COLUMNS - SPACING
}

return (
  <View style={grid}>
    {this.props.things.map(thing => <View style={cell} />)}
  </View>
)
Run Code Online (Sandbox Code Playgroud)

如果您有已知且数量有限的项目,则应该只使用此技术 - 对于任意数量的卡片,您应该ListView出于性能原因使用,并手动将数据集拆分为行.


Che*_*niv 9

React Native已经拥有百分比支持:

<View style={[style.parent]}>
    <View style={[style.child, {backgroundColor: '#996666'} ]} />
    <View style={[style.child, {backgroundColor: '#339966'} ]} />
    <View style={[style.child, {backgroundColor: '#996633'} ]} />
    <View style={[style.child, {backgroundColor: '#669933'} ]} />
</View>

var style = StyleSheet.create({
    parent: {
        width: '100%', 
        flexDirection: 'row', 
        flexWrap: 'wrap'
    },
    child: {
        width: '48%', 
        margin: '1%', 
        aspectRatio: 1,
    }
})
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述