How do I center an item within a React Native ListView?

后端 未结 2 1321
南方客
南方客 2021-02-10 08:12

I\'m trying to center an item within a horizontal listView when selected. My current strategy is to first measure the item and scroll to the x coordinates of the referenced item

相关标签:
2条回答
  • 2021-02-10 09:03

    In my opinion, you should use FlatList

    FlatList have a method scrollToIndex that allows to directly go to an item of your datas. It's almost the same as a ScrollView but smarter. Sadly the documentation is very poor.

    Here is an example of a FlatList I did

    let datas = [{key: 0, text: "Hello"}, key: 1, text: "World"}]
    
    <FlatList
        // Do something when animation ended
        onMomentumScrollEnd={(e) => this.onScrollEnd(e)} 
        ref="flatlist"
        showsHorizontalScrollIndicator={false}
        data={this.state.datas}
        keyExtractor={(item) => item.key}
        getItemLayout={(data, index) => (
            // Max 5 items visibles at once
            {length: Dimensions.get('window').width / 5, offset: Dimensions.get('window').width / 5 * index, index}   
        )}
        horizontal={true}
        // Here is the magic : snap to the center of an item
        snapToAlignment={'center'}  
        // Defines here the interval between to item (basically the width of an item with margins)
        snapToInterval={Dimensions.get('window').width / 5}    
        style={styles.scroll}
        renderItem={ ({item}) =>
            <TouchableOpacity
                onPress={() => this.scrollToIndex(/* scroll to that item */)}
                style={styles.cell}>
                <Text>{item.text}</Text>
            </TouchableOpacity>
        }
    />
    

    More about FlatList : https://facebook.github.io/react-native/docs/flatlist#__docusaurus

    0 讨论(0)
  • 2021-02-10 09:10
    flatlistRef.current.scrollToIndex({
                        animated: true,
                        index,
                        viewOffset: Dimensions.get('window').width / 2.5,
                      });
    

    You can try to put viewOffset inside the scrollToIndex property, it will handle your component offset, I use 2.5 to make it in middle of screen , because I show 5 item each section and one of focused item will be in middle of screen

    0 讨论(0)
提交回复
热议问题