ReactNative实现GridView

ReactNative内置了ListView组件但是没有类似GridView这样的组件。利用一些已经有的属性是可以实现GridView的,利用ContentContainerStyle的属性然后配合样式就可以实现GridView

import React, {Component} from 'react';
import {
    StyleSheet,
    Text,
    View,
    ListView,
    TouchableWithoutFeedback
} from 'react-native';
const styles = StyleSheet.create({
    contentContainerStyle: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        alignItems: 'flex-start',
        justifyContent: 'space-between'
    },
});
export default class GridView extends Component {
    constructor(props) {
        super(props);
        let dividerHorizontal = this.props.dividerHorizontal ? this.props.dividerHorizontal : 0;
        let column = this.props.column ? this.props.column : 2;
        let emptyDataSource = new ListView.DataSource({
            rowHasChanged: (r1, r2)=>r1 != r2
        })
        this.state = {
            'dataSource': emptyDataSource,
            'column': column,
            'viewWidth': 0,
            'dividerHorizontal': dividerHorizontal
        };
    }
    _renderItem(data) {
        let viewWidth = this.state.viewWidth;
        let column = this.state.column;
        let dividerHorizontal = this.state.dividerHorizontal;
        let itemWidth = (viewWidth - (dividerHorizontal * column - dividerHorizontal)) / column;
        let renderItem = this.props.renderItem;
        return (
            <View style={{width: itemWidth}}>
                {
                    renderItem && renderItem(data)
                }
            </View>
        );
    }
    render() {
        let refreshControl = this.props.refreshControl ? this.props.refreshControl : null;
        return (
            <View
                style={{flex: 1}}
                onLayout={(event)=> {
                    let width = event.nativeEvent.layout.width;
                    if (!width || width === this.state.viewWidth)
                        return;
                    this.setState({
                        'viewWidth': width,
                        'dataSource': this.props.dataSource
                    })
                }}>
                <ListView
                    style={{flex: 1}}
                    contentContainerStyle={styles.contentContainerStyle}
                    dataSource={this.state.dataSource}
                    renderRow={this._renderItem.bind(this)}
                    refreshControl={refreshControl}
                />
            </View>
        );
    }
}



《架构文摘》每天一篇架构领域重磅好文,涉及一线互联网公司应用架构(高可用、高性 能、高稳定)、大数据、机器学习等各个热门领域。

posted @   架构文摘  阅读(4299)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端
点击右上角即可分享
微信分享提示