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
相关推荐
今禾1 分钟前
深入理解 JavaScript 事件监听机制
前端·javascript
FogLetter1 分钟前
从饼干到Cookie:前端存储的身份密码本
前端·javascript
Mintopia10 分钟前
LOD:图形世界里的 “看人下菜碟” 艺术
前端·javascript·计算机图形学
Code季风12 分钟前
SQL关键字快速入门:CASE 实现条件逻辑
javascript·数据库·sql
Mintopia14 分钟前
Three.js ArrowHelper:三维世界里的 “方向向导”
前端·javascript·three.js
Jacob023420 分钟前
JavaScript 模块系统二十年:混乱、分裂与出路
前端·javascript
qianbo_insist22 分钟前
c++ python 共享内存
开发语言·c++·python
今天背单词了吗98036 分钟前
算法学习笔记:8.Bellman-Ford 算法——从原理到实战,涵盖 LeetCode 与考研 408 例题
java·开发语言·后端·算法·最短路径问题
CoderPractice42 分钟前
C#控制台小项目-飞行棋
开发语言·c#·小游戏·飞行棋