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
相关推荐
似水流年 光阴已逝2 分钟前
从Excel姓名匹配案例学Python:由点及面的系统化学习指南
开发语言·python·excel
重生之我要当java大帝5 分钟前
java微服务-尚医通-管理平台前端搭建-医院设置管理-4
java·开发语言·前端
我是日安8 分钟前
从零到一打造 Vue3 响应式系统 Day 27 - toRef、toRefs、ProxyRef、unref
前端·javascript·vue.js
Q_Q196328847516 分钟前
python+vue的在线租房 房屋租赁系统
开发语言·vue.js·spring boot·python·django·flask·node.js
不如喫茶去24 分钟前
VUE查询-历史记录功能
前端·javascript·vue.js
一枚前端小能手44 分钟前
「周更第8期」实用JS库推荐:decimal.j
前端·javascript
东巴图1 小时前
分解如何利用c++修复小程序的BUG
开发语言·c++·bug
祁同伟.1 小时前
【C++】二叉搜索树(图码详解)
开发语言·数据结构·c++·容器·stl
恒者走天下1 小时前
AI智能网络检测项目(cpp c++项目)更新
开发语言·c++
Tech_Lin1 小时前
JavaScript Date时间对象的常用操作方法总结
前端·javascript