Rn使用FlatList导航栏自动回到中间

js 复制代码
import { useState, useRef } from 'react'
import { FlatList, View, Text, StyleSheet, TouchableOpacity } from 'react-native'

const Center = () => {
    const tabs = ["语文", "数学", "英语", "政治", "历史", "地理"]
    const [active, setActive] = useState(0)
    const flatRef = useRef()

    const activeTab = (index) => {
        setActive(index)
        flatRef.current.scrollToIndex({ viewPosition: 0.5, index: index, animated: true })
    }

    return (
        <>
            <View style={styles.nav}>
                <FlatList data={tabs} ref={flatRef} horizontal showsHorizontalScrollIndicator={false}
                    renderItem={({ item, index }) => (
                        <TouchableOpacity key={index} onPress={() => activeTab(index)}
                            style={[
                                styles.nav_item,
                                active == index && styles.nav_item_active,
                                tabs.length - 1 == index && styles.nav_item_last
                            ]}>
                            <Text style={active == index && styles.nav_item_active_text}>
                                {item}
                            </Text>
                        </TouchableOpacity>
                    )}
                />
            </View>
        </>
    )
}

const styles = StyleSheet.create({
    nav: {
        height: 45,
        flexDirection: "row",
        alignItems: "center",
        borderBottomColor: "#eee",
        borderBottomWidth: 1,
        paddingHorizontal: 10
    },
    nav_item: {
        paddingHorizontal: 20,
        paddingVertical: 4,
        borderColor: "#DADCE2",
        borderWidth: 1,
        borderRadius: 20,
        alignItems: "center",
        justifyContent: "center",
        marginRight: 10
    },
    nav_item_last: {
        marginRight: 0
    },
    nav_item_active: {
        backgroundColor: "#2C72FF",
        borderColor: "transparent",
    },
    nav_item_active_text: {
        color: "#ffffff"
    }
})

export default Center
相关推荐
小高不明12 分钟前
前缀和一维/二维-复习篇
开发语言·算法
龘龍龙16 分钟前
Python基础(八)
开发语言·python
栀秋6661 小时前
防抖 vs 节流:从百度搜索到京东电商,看前端性能优化的“节奏哲学”
前端·javascript
有意义1 小时前
深入防抖与节流:从闭包原理到性能优化实战
前端·javascript·面试
幺零九零零1 小时前
Golang-Swagger
开发语言·后端·golang
2503_928411562 小时前
12.26 小程序问题和解决
前端·javascript·微信小程序·小程序
over6972 小时前
防抖与节流:前端性能优化的“双子星”,让你的网页丝滑如德芙!
前端·javascript·面试
陌路物是人非2 小时前
记一个 @Resource BUG
java·开发语言·bug
怎么就重名了2 小时前
记录Qt的UDP通信丢包问题
开发语言·qt·udp
red润2 小时前
手把手封装Iframe父子单向双向通讯功能
前端·javascript·vue.js