简体   繁体   中英

How to animate reorder with React Native FlatList?

I have some UI that looks like this:

在此处输入图片说明

These list items can be: (1) added, (2) deleted, (3) reordered.

The reordering is not drag and drop, but happens when clicking the check/empty circle icons - the checked items always stay at the top of the list.

There are many examples of animating adding/removing items from lists in React Native ( here's one such example ).

But how can I animate the ordering of a list? Specifically in my case, it would be two list items swapping position.

I have seen react-native-sortable-list and a few other open source projects, but I think this is probably overkill as I do not need drag and drop. Also, I am already hooking into some FlatList events like onLayout , onContentSizeChange , and onScroll , so I would prefer a solution that allows me to animate the children of a FlatList directly.

The flatlist is sorted in order of the array that you feed it through the data prop. Whether you are using component-level state (ie this.state ) or redux to manage your state, you can reorder the array of elements and it should rerender in that order. For example, one implementation may be:

const checkedData = [...this.state.data].filter(item => item.checked === true);
const uncheckedData = [...this.state.data].filter(item => item.checked !== true);
const sortedData = checkData.concat(uncheckedData);
this.setState({ data: sortedData });

The javascript filter function should preserve original sort order of the subset.

To animate it, you can then look into LayoutAnimation in react native. It will apply an animation type to every change in your view between renders.

Just wanted to add onto Nth.gol 's answer which helped me solve the same issue.

To animate the list in simple way:

  1. Update the state of the list to the new state you wish to animate to

  2. Add this line above the state update:

    LayoutAnimation.configureNext(LayoutAnimation.Presets.spring);

  3. To make sure the animation also works on Andriod add this code outside of your constructor:

if (Platform.OS === 'android' && UIManager.setLayoutAnimationEnabledExperimental) {
    UIManager.setLayoutAnimationEnabledExperimental(true);
}

Note: You will need to import LayoutAnimation && UIManager from react-native

There are many options for configuring the duration & type of animation, but this is a nice & simple working solution. You can read more about the configuration options here: LayoutAnimation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM