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
相关推荐
C、空白格2 分钟前
Java集成Vosk实现离线语音识别
java·开发语言·语音识别
编码浪子11 分钟前
基于 Rust + Axum 的企业级权限管理系统设计与实现
开发语言·后端·rust
历程里程碑14 分钟前
MySQL事务深度解析:ACID到MVCC实战+万字长文解析
开发语言·数据结构·数据库·c++·sql·mysql·排序算法
Lyyaoo.21 分钟前
【JAVA基础面经】native方法
java·开发语言
牛十二23 分钟前
nacos2.4连接出错源码分析
java·linux·开发语言
|晴 天|29 分钟前
Vue 3 实现实时通知系统:支持未读计数、红点提醒、一键已读
javascript·vue.js·ecmascript
小松加哲31 分钟前
AspectJ编译期织入实战
java·开发语言
鲸渔32 分钟前
【C++ 跳转语句】break、continue、goto 与 return
开发语言·c++·算法
大流星36 分钟前
敲黑板!async/await应用原理
前端·javascript
喜欢吃燃面1 小时前
Linux 进程信号深度解析:从概念到产生机制
linux·开发语言·学习