2016-01-22 37 views
7

在过去的几周内,在iOS上反应原生态后,我似乎遇到了flex样式的一些缺陷......特别是当涉及到“响应”行为时。例如,假设您想要创建一个包含卡片的视图(这些卡片的元数据来自API)。你想要的卡是视图宽度减去余量&填充的50%,并且至包装每个2.反应原生Flexbox - 如何做百分比||列||响应式||网格等

enter image description here

当前实现我对这个视图分裂返回的数组与2行后项目。列表容器有flex: 1, flexDirection: 'column,行有flex: 1,然后每张卡片有flex: 1。最终结果是每行有2列,均匀占据视图宽度的一半。

似乎在React Native样式中没有无关紧要的方法,不使用JavaScript对数据进行某种预处理,使其正确显示样式。有没有人有什么建议?

+0

你尝试 “flexWrap”? –

+0

是的,但flexWrap只在儿童发生溢出时才起作用,只有在儿童指定宽度属性时才能触发。 @niceass –

+0

指定50%宽度有什么问题?这不正是你想要的吗? –

回答

1

阵营已经原住民has percentage support

<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, 
    } 
}) 

enter image description here

17

有可能是一个更好的方式与Flexbox的实现这一点,但我通常定义视宽,视高“百分比”助手vwvh,测量的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); 
} 

在网格中流动的物品,就可以计算出项目的适当大小,占利润和视口大小:

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> 
) 

时,才应使用这个技术,如果你有一个已知的和LIMITE d数量的项目 - 对于任意数量的卡片,出于性能原因,您应该使用ListView,并将数据集手动分割为行。

+0

这似乎是迄今为止最好的解决方案。感谢您分享@jevakallio。 –

+1

这种方法的问题在于,如果允许更改方向,它将不起作用。 – Joon

+0

@Joon correct - 我刚刚发布了一个库,可以更方便地在横向和纵向上对原生组件进行样式设置:https://github.com/FormidableLabs/react-native-responsive-styles – jevakallio

0

您可以使用justifyContent: '空间' 之间

<View style={styles.feed}> 
    <View style={styles.card} /> 
    <View style={styles.card} /> 
    <View style={styles.card} /> 
    <View style={styles.card} /> 
</View> 

feed: { 
flex: 1, 
flexDirection: 'row', 
flexWrap: 'wrap', 
padding: 16, 
justifyContent: 'space-between' } 


card: { 
backgroundColor: 'white', 
width: '48%', 
aspectRatio: 1, 
marginBottom: 16 } 

screenshot