第八章、ReactNative 用ListView实现GridView效果

本文介绍了如何在ReactNative中使用ListView组件实现GridView效果。通过示例代码详细展示了数据构造和GridView封装的关键步骤,适用于需要在应用中创建网格布局的开发者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ReactNative 用ListView实现GridView效果

直接上代码,多说无用. 先构造数据;

//构造数据
request() {
    const rowData = Array.from(new Array(15))
            .map((value, index) => ({text: "item " + index, clicked: 0}))
            .concat(this.state.listData);

    this.setState({
            isRefresh: false,
            listData: rowData,
        });
    }

根据实际情况封装你的GridView,这里简单展示实现的关键点

//关键点是定义flexDirection:"row",flexWrap:"wrap"这两个属性. 
GridView = (column,margin) => {
    return <ListView

        //显示竖直滚动条
        showsVerticalScrollIndicator = { true }

        //定义content的样式,这里是 contentContainerStyle,而不是style
        contentContainerStyle={{
        width: Dimensions.get("window").width,
        backgroundColor: "#ffffff",
        flexDirection: "row",
        flexWrap: "wrap",
        alignItems:"center" }}

        //数据源
        dataSource={this.state.dataSource.cloneWithRows(this.state.listData)}

        //渲染Item
        renderRow={(rowData, index) => {
        let w = ( Dimensions.get("window").width - column * margin * 2 )
         / column;

        //这里是自已定义的ItemView
        return <CButton key={index} style={{width: w, height: 50,
        borderRadius: 5, margin: margin}} onPress={() => {
            ToastAndroid.show(rowData.text, ToastAndroid.SHORT)
        }} text={rowData.text}/>
        }}
        />
    }

然后在render数中调用这个方法即可

   render(){
       <View>
           ... ... 
           {this.GridView(3,5)}
           ... ...
       </View>
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值