对动态元素不起作用的本机两列布局进行反应

时间:2017-01-19 14:15:16

标签: react-native flexbox

内部带有图像的多个视图元素需要以两列布局显示。

我正在使用以下代码(基本上,获取窗口的尺寸(x)并设置View width = x / 2)。

父容器为flex: row

但这似乎不起作用。我连续只获得一个图像而不是图像中显示的两个图像。我做错了什么?

const window = Dimensions.get('window');
const imageWidth = (window.width/3)+30;
const imageHeight = window.width/3;
export default class Brochures extends Component {
  render() {
    const brochuresView = brochuresData.map( Brochure );
    return (
      <ScrollView style={styles.container}>
        {brochuresView}
      </ScrollView>
    );
  }
}

const Brochure = ( data ) => {
  const {child, image} = styles;
  return (
    <View key={data.id} style={child}>
      <Image
        style={image}
        source={{uri: data.url}}
      />
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    flexWrap: 'wrap'
  },
  child: {
    width: window.width/2,
    alignItems: 'center',
    height: imageHeight+5,
    marginTop: 10
  },
  image: {
    width: imageWidth,
    height: imageHeight
  }
});

Wrong layout

2 个答案:

答案 0 :(得分:4)

ScrollView采用contentContainerStyle道具与正常style道具来描述造型。

来自文档:

  

这些样式将应用于滚动视图内容容器   它包装了所有子视图。例如:

     

return ( <ScrollView contentContainerStyle={styles.contentContainer}> </ScrollView> ); ... const styles = StyleSheet.create({ contentContainer: { paddingVertical: 20 } });

因此,基本上您需要对代码进行的唯一更改是:

<ScrollView contentContainerStyle={styles.container}>

vs this:

<ScrollView style={styles.container}>

答案 1 :(得分:0)

试试这个:

const window = Dimensions.get('window');
const imageWidth = (window.width/3)+30;
const imageHeight = window.width/3;
export default class Brochures extends Component {
  render() {
    const brochuresView = brochuresData;
    var brochuresRow = [];
    var set = [];
    var setCounter = 0;

    for(var i = 0; i < brochuresView.length; i++) {
        set.push(brochuresView[i]);
        if((i + 1) % 2 == 0 || (i + 1) >= brochuresView.length) {
            setCounter++;
            brochuresRow.push(set);
            set = [];
        }
    }

    return (
      <ScrollView>
        {brochuresRow.map((row, i) => (
            <View key={i} style={styles.container}>
                {row.map((brochure, ii) => (
                    <View key={ii} style={styles.child}>
                        <Image
                            style={styles.image}
                            source={{uri: brochure.url}}
                        />
                    </View>
                ))}
            </View>
        ))}
      </ScrollView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    flex: 1,
    justifyContent: 'center'
  },
  child: {
    height: imageHeight+5,
    marginTop: 10
  },
  image: {
    width: imageWidth,
    height: imageHeight
  }
});