React Native FlatList 选中效果 多选

最近写项目碰到了列表的多选需求,开始我直接用setState并不会直接起作用,只会在改变的item移出渲染区然后重新渲染的时候才会有效果,后来查看文档才发现有一extraData的参数。需要设置才能在setState之后马上渲染

效果图.gif

代码如下

import React, {Component} from 'react';
import {
    Image,
    Text,
    View,
    TouchableHighlight,
    FlatList,
    StyleSheet,
    Button
} from 'react-native';
export default class TestFlatListSelect extends Component {
    constructor(props) {
        super(props)
        this.state = {
            data: [{
                "id": "0",
                select: false
            },
                {
                    "id": "1",
                    select: false
                },
                {
                    "id": "2",
                    select: false
                },
                {
                    "id": "3",
                    select: true
                },
                {
                    "id": "4",
                    select: true
                },
                {
                    "id": "5",
                    select: true
                }
],//数据源
            selectItem: [],
        }
    }

    _itemPress = (item) => {
        console.log(item);
    }
    _selectItemPress = (item) => {
        if (item.select) {
         this.state.selectItem.splice(this.state.selectItem.findIndex(function (x) {
                return x === item.name;
            }))
        } else {
            this.state.selectItem.push(item)
        }
        this.state.data[item.id].select = !item.select
        // this.state.data=arr.pop()
        this.setState({data: this.state.data})
    }

    _submitPress() {
        alert(`选中了${JSON.stringify(this.state.selectItem)}`)
    }
    render() {
        return (
             item.id}
                data={this.state.data}
                extraData={this.state} //这里是关键,如果不设置点击就不会马上改变状态,而需要拖动列表才会改变
                ListHeaderComponent={({item}) => {
                    return (

你可能感兴趣的:(React Native FlatList 选中效果 多选)