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
相关推荐
娇娇yyyyyy10 分钟前
QT编程(17): Qt 实现自定义列表模型
开发语言·qt
ms_27_data_develop26 分钟前
Java枚举类、异常、常用类
java·开发语言
add45a41 分钟前
C++编译期数据结构
开发语言·c++·算法
前端Hardy1 小时前
Wails v3 正式发布:用 Go 写桌面应用,体积仅 12MB,性能飙升 40%!
前端·javascript·go
Highcharts.js1 小时前
Highcharts React v4 迁移指南(下):分步代码示例与常见问题解决
javascript·react.js·typescript·react·highcharts·代码示例·v4迁移
Laurence1 小时前
Qt 前后端通信(QWebChannel Js / C++ 互操作):原理、示例、步骤解说
前端·javascript·c++·后端·交互·qwebchannel·互操作
岁岁种桃花儿1 小时前
AI超级智能开发系列从入门到上天第四篇:AI应用方案设计
java·服务器·开发语言
Pu_Nine_91 小时前
JavaScript 字符串与数组核心方法详解
前端·javascript·ecmascript
Amnesia0_01 小时前
C++中的IO流
开发语言·c++
2401_891482171 小时前
C++模块化编程指南
开发语言·c++·算法