[RN] React Native 让 Flatlist 支持 选中多个值,并获取所选择的值

React Native 让 Flatlist  支持  选中多个值,并获取所选择的值

 

实现效果如下:

 [RN] React Native 让 Flatlist 支持 选中多个值,并获取所选择的值_第1张图片

 

实现代码:

import React, {Component} from 'react';
import {
    Image,
    Text,
    View,
    TouchableOpacity,
    FlatList,
    StyleSheet,
    Button
} from 'react-native';

export default class TestListCheck extends Component {
    constructor(props) {
        super(props);
        this.state = {
            data: [
                {
                    "id": "0",
                    select: false
                },
                {
                    "id": "1",
                    select: false
                },
                {
                    "id": "2",
                    select: false
                },
                {
                    "id": "3",
                    select: false
                },
                {
                    "id": "4",
                    select: false
                },
                {
                    "id": "5",
                    select: false
                }
            ],//数据源
            selectItem: [],
        }
    }

    _selectItemPress(item) {
        if (item.select) {
            this.state.selectItem.splice(this.state.selectItem.findIndex(function (x) {
                return x === item.id;
            }), 1);
        } else {
            this.state.selectItem.push(item.id);
        }
        this.state.data[item.id].select = !item.select;
        this.setState({data: this.state.data})
    }

    _submitPress() {
        alert(`选中了${JSON.stringify(this.state.selectItem)}`)
    }

    render() {
        return (
            <FlatList
                keyExtractor={item => item.id}
                data={
     this.state.data}
                extraData={
     this.state} //这里是关键,如果不设置点击就不会马上改变状态,而需要拖动列表才会改变
                ListHeaderComponent={({item}) => {
                    return (

 

本博客地址: wukong1688

本文原文地址:https://www.cnblogs.com/wukong1688/p/11080603.html

转载请著名出处!谢谢~~

转载于:https://www.cnblogs.com/wukong1688/p/11080603.html

你可能感兴趣的:([RN] React Native 让 Flatlist 支持 选中多个值,并获取所选择的值)