React Native 單選,複選, 全選功能

簡單寫了一個ListView數據的單選和全選,刪除功能

  1. 利用JS的Map對象進行勾選,取消勾選和全選
  2. 方法簡單粗暴
  3. 單選功能見註釋的 單選邏輯 , 單選功能不做全選
  4. 其餘未註釋的代碼爲複選和全選功能
/**
 * Created by zhuang.haipeng on 2017/9/12.
 */
import React, {Component} from 'react';
import {
    StyleSheet,
    View,
    TouchableOpacity,
    Dimensions,
    ListView,
    Text,
    Image
} from 'react-native';

const {width, height} = Dimensions.get('window');

var collectionArray = [
    {collectItem: "collectItem1"},
    {collectItem: "collectItem2"},
    {collectItem: "collectItem3"},
    {collectItem: "collectItem4"},
    {collectItem: "collectItem5"},
    {collectItem: "collectItem6"},
    {collectItem: "collectItem7"},
    {collectItem: "collectItem8"},
    {collectItem: "collectItem9"},
    {collectItem: "collectItem10"}
];

export default class extends React.Component {

    constructor(props) {
        super(props);

        const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        this.state = {
            dataSource: ds.cloneWithRows([]),
            isEdit: false,
            isChecked: false,
            isAllSelect: false,
            isShowBottom: false,
            selectMap: new Map(),
            // preIndex: 0 // 聲明點擊上一個按鈕的索引  **** 單選邏輯 ****
        };
    }

    componentDidMount() {
        this.setState({
            dataSource: this.state.dataSource.cloneWithRows(collectionArray)
        })
    }

    render() {
        let temp = [...this.state.selectMap.values()];
        let isChecked = temp.length === this.state.dataSource._cachedRowCount;

        console.log(temp, '......')
        return (
            <View style={{flex:1}}>
                <View style={{width: width, height: 64, backgroundColor:"#FFF",
                justifyContent:"flex-end", paddingRight: 20, flexDirection:'row', alignItems:"center"}}>
                    <TouchableOpacity onPress={() => this.editClick()}>
                        <Text>編輯</Text>
                    </TouchableOpacity>
                </View>
                <ListView
                    renderRow={this.renderRow}
                    dataSource={this.state.dataSource}

                >
                </ListView>
                {
                    this.state.isShowBottom == true ?
                        <View style={{width: width, height: 49, backgroundColor:"#FFF",
                justifyContent:"space-between", paddingRight: 20, flexDirection:'row', alignItems:"center"}}>
                            <TouchableOpacity style={{flexDirection:'row'}} onPress={() => this.allSelect(isChecked)}>
                                <Image style={{marginLeft:10}} source={isChecked ? require("../img/mine/ic_select.png") :
                            require("../img/mine/ic_unselect.png")}/>
                                <Text style={{marginLeft:10, color: "#cc3341", marginTop:5}}>全選</Text>
                            </TouchableOpacity>
                            <TouchableOpacity onPress={() => this.deleteItem()}>
                                <Text style={{marginRight: 20, color:"#cc3341"}}>刪除</Text>
                            </TouchableOpacity>
                        </View> : null
                }
            </View>
        );
    }

    renderRow = (rowData, sectionID, rowID) => { // cell樣式

        let map = this.state.selectMap;
        let isChecked = map.has(parseInt(rowID))
        // 選中的時候, 判斷上一個索引不等於rowID的時候,不讓他選中   **** 單選邏輯 ****
        // let isChecked = parseInt(rowID) == this.state.preIndex ?  map.has(parseInt(rowID)) : false; // 將rowID轉成Int,然後將Int類型的ID當做Key傳給Map

        return (
            <View style={{width: width, height: 60, backgroundColor:"#EEEEDD",
             marginBottom: 10, alignItems:"center", justifyContent:'center', marginLeft: this.state.isEdit ? 40 : 0}}>
                {
                    this.state.isEdit ?
                        <TouchableOpacity style={{position:'absolute', left:-30}} onPress={
                        () => this.selectItem(parseInt(rowID), rowData.collectItem ,isChecked)}>
                            <Image source={isChecked ? require("../img/mine/ic_select.png") :
                            require("../img/mine/ic_unselect.png")}/>
                        </TouchableOpacity> : null
                }
                <Text>{rowData.collectItem}</Text>
            </View>
        )
    }

    editClick = () => { // 編輯
        this.setState({
            isEdit: !this.state.isEdit,
            selectMap: new Map()
        }, () => {
            this.setState({
                isShowBottom: this.state.isEdit ? true : false
            })
        })
    };

    deleteItem = () => { // 刪除
        let {selectMap} = this.state;
        let valueArr = [...selectMap.values()];
        let keyArr = [...selectMap.keys()];
        alert("刪除" + valueArr)
    };

    allSelect = (isChecked) => { // 全選
        this.setState({
            isAllSelect: !isChecked
        });
        if (isChecked) { // 如果已經勾選了,則取消選中
            let {selectMap} = this.state;
            selectMap = new Map();
            this.setState({selectMap})
        } else { // 沒有勾選的, 全部勾選
            let newMap = new Map();
            for (let key = 0; key < collectionArray.length; key++) {
                let value = collectionArray[key].collectItem; // 拿到數組的collectItem
                newMap.set(key, value) // 第一個key, 第二個是value
            }
            this.setState({selectMap: newMap})
        }
    }

    selectItem = (key, value, isChecked) => { // 單選

        this.setState({
            isChecked: !this.state.isChecked,
            // preIndex: key  //  **** 單選邏輯 ****
        }, () => {
            let map = this.state.selectMap;
            if (isChecked) {
                map.delete(key, value) // 再次點擊的時候,將map對應的key,value刪除
            } else {
                // map = new Map() // ------>   **** 單選邏輯 ****
                map.set(key, value) // 勾選的時候,重置一下map的key和value
            }
            this.setState({selectMap: map})
        })
    }
};

這裏寫圖片描述 這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章