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+-C资深大佬3 分钟前
python while循环
服务器·开发语言·python
Tian_Hang4 分钟前
eclipse ditto 学习笔记
运维·服务器·开发语言·javascript·3d
星夜夏空9914 分钟前
C++学习(2) —— 类与对象基础
开发语言·c++·学习
倒流时光三十年35 分钟前
Java 内存模型(JMM)通俗解释
java·开发语言
码兄科技1 小时前
Java AI智能体开发实战:从零构建企业级智能应用指南
java·开发语言·人工智能
zh路西法1 小时前
【现代控制理论与卡尔曼滤波】从状态空间到Python仿真实现
开发语言·python
Evand J1 小时前
【论文复现】MATLAB例程,存在测距误差的WSN无锚点分布式自定位,《WSN中存在测距误差的无锚点分布式自定位方法》
开发语言·分布式·matlab·定位·导航·wsn
techdashen2 小时前
kTLS 进入 rustls 组织:把 TLS 的数据面交给内核
开发语言·php
Lhappy嘻嘻2 小时前
Java 并发编程(六)|并发进阶高频:CAS、锁升级
java·开发语言
techdashen2 小时前
Arborium:把 tree-sitter 语法高亮打包成 Rust 文档生态的基础设施
开发语言·后端·rust