首页 > 解决方案 > 如何水平显示具有 2 列的 Scrollview 图像

问题描述

嗨,我想水平显示具有 2 列的图像,我正在使用滚动视图,但我不知道该怎么做,我正在使用以下代码

获取api的代码

 componentDidMount(){
return fetch('https://www.json-generator.com/api/json/get/ccLAsEcOSq?indent=1')
  .then((response) => response.json())
  .then((responseJson) => {
    this.setState({
      isLoading: false,
      dataSource: responseJson.book_array,
    }, function(){
    });
  })
  .catch((error) =>{
    console.error(error);
  });

}

渲染代码

render() {
if (this.state.isLoading === true) {
  return <ActivityIndicator color={'red'} />;
}
return (
  <View style={styles.container}>
    <ScrollView horizontal={true}>
      {this.state.dataSource.map(item => this.renderItem(item))}
    </ScrollView>
  </View>
);

} }

renderItem 的代码

renderItem(item) {
return (
  <View style={{ margin: 5 }}>
    <View style={{
        backgroundColor: 'red',
        width: 150,
        height: 150,
        marginBottom: 1,
      }}>
       <Image  style={{ width: 150,height: 150}}
                      source={{uri: item.image}}/>  
    </View> 

    <View style={{
        backgroundColor: 'red',
        width: 150,
        height: 150,
        marginBottom: 1,
      }}>
       <Image  style={{ width: 150,height: 150}}
                      source={{uri: item.image}}/>  
    </View> 

  </View>
);}

标签: react-native

解决方案


而不是ScrollViewtry FlatListwhich 提供numColumns道具,让您允许根据您的选择使用列。

取而代之的是,

<ScrollView horizontal={true}>
      {this.state.dataSource.map(item => this.renderItem(item))}
</ScrollView>

用这个,

<FlatList 
   data={this.state.dataSource}
   numColumns={2}
   renderItem={this.renderItem}
/>

有关详细信息,FlatList请参见此处的官方文档


推荐阅读