1. 程式人生 > >React Native ListView 長按刪除

React Native ListView 長按刪除

專案中React Native ListView的長按刪除功能分享(基於ES5):

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, {Component} from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    ListView,
    TouchableOpacity
} from 'react-native';

var ds = new ListView.DataSource({
    rowHasChanged: (r1, r2) => {
        r1 !== r2
    }
});

var rows = ['row 1', 'row 2', 'row 3', 'row 4', 'row 5', 'row 6'];

var XXX = React.createClass({

    getInitialState() {
        return {
            dataSource: ds.cloneWithRows(rows),
        };
    },

    _deleteRow(rowID) {
        delete rows[rowID];
        this.setState({dataSource: ds.cloneWithRows(rows)})
    },

    renderRow(rowData, sectionID, rowID) {
        return <TouchableOpacity onLongPress={()=>this._deleteRow(rowID)}
                                 style={{height: 60, flex: 1, borderBottomWidth: 1}}>
            <Text>{rowData}</Text>
        </TouchableOpacity>
    },

    render() {
        return (
            <ListView
                dataSource={this.state.dataSource}
                renderRow={this.renderRow}
            />
        );
    }



});

AppRegistry.registerComponent('XXX', () => XXX);

補充1:JS的刪除方法除了delete刪除不改變陣列長度外,還有splice等方法。


補充2:rowHasChanged是 react native 元件紀錄 state 是否更新的一個方法,等於或不等於並不影響你第一次顯示,影響的是你state變化以後的顯示情況。如果是等於,state變化 頁面不更新 , state不變,才更新(一般不用)。不等於就是 state變化 頁面立即更新。
rowHasChanged即sectionID,react將資料封裝成了新物件,key叫s1 s2 ... ,列印rowHasChanged或者sectionID即輸出s1 s2 ...


補充3:如果ListView中有enableEmptySections = {true}屬性,字面理解為可以使ListView的元素item為空。測試:刪除最後一個item,debug模式下會報一個警告,如下圖。


react native官方後續還會優化這塊