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
相关推荐
木易 士心几秒前
Node.js 性能诊断利器 Clinic.js:原理剖析与实战指南
开发语言·javascript·node.js
一只乔哇噻1 分钟前
java后端工程师+AI大模型进修ing(研一版‖day59)
java·开发语言·算法·语言模型
不老刘1 分钟前
深入理解 React Native 的 Metro
javascript·react native·react.js·metro
哆啦A梦15881 分钟前
67 token 过期时间
前端·javascript·vue.js·node.js
报错小能手2 分钟前
C++流类库 概述及流的格式化输入/输出控制
开发语言·c++
2301_789015624 分钟前
C++:list(带头双向链表)增删查改模拟实现
c语言·开发语言·c++·list
萌狼蓝天4 分钟前
[Vue]AntV1.7表格自带筛选确定和重置按钮位置交换
前端·javascript·css·vue.js·html
扣脚大汉在网络7 分钟前
关于一句话木马
开发语言·网络安全
by__csdn7 分钟前
Axios封装实战:Vue2高效HTTP请求
前端·javascript·vue.js·ajax·vue·css3·html5
学习路上_write9 分钟前
FREERTOS_定时器——创建和基本使用
c语言·开发语言·c++·stm32·嵌入式硬件