How to select item(s) out of a FlatList?

2019-04-13 01:33发布

问题:

I want to select items using FlatList like when you select multiple photos on your photo galery (in this case, I am using a flatlist with 2 rows like a grid of 2x10). I want to select (for example) 3 items using onLongPress.

Something like this, but with 2 rows.

回答1:

What about this:

Every item rendered would have an onLongPress, and an isPicked property.

Initially, and in renderItem(), you would implement an if statement that either renders checked square or empty square every time an item executes executes; To indicate if the item is selected or not (based on isPicked).

onLongPress invokes isPicked and rerenders everything (to toggle the square). So if isPicked is true it becomes false, and if false becomes true. You can achieve that by simply doing this: this.item.isPicked = !this.item.isPicked

Finally on Submit, filter all your initial items (data) by the isPicked === true and hurrah, you will end up with the items that were selected !