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
相关推荐
baozj4 分钟前
一次表单数据复用引发的 Bug:理解 Vue 中的 data 为何是函数
前端·javascript·vue.js
LRH6 分钟前
JS基础 - instanceof 理解及手写
前端·javascript
小小神仙9 分钟前
JSCommon系列 - 为什么前端没有 Apache Commons?
前端·javascript·设计模式
一头小鹿10 分钟前
【JS】手写显示绑定改变this指向的方法call、apply、bind | 笔记整理
javascript
Sun_light10 分钟前
深入理解 JavaScript 对象:从入门到精通
前端·javascript
中微子11 分钟前
从零构建电影展示页面:原生js Web开发技术解析
前端·javascript
Mintopia16 分钟前
计算机图形学中的几何体布尔运算:一场形状的奇幻冒险
前端·javascript·计算机图形学
Mintopia21 分钟前
Three.js 动态加载 GLTF 模型:高效加载和渲染复杂的 3D 模型
前端·javascript·three.js
std787922 分钟前
VITA STANDARDS LIST,VITA 最新标准清单大全下载_ansi vita 2025
java·前端·javascript
wen's24 分钟前
React Native 弹窗组件优化实战:解决 Modal 闪烁与动画卡顿问题
javascript·react native·react.js