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
相关推荐
开发者小天4 分钟前
react的组件库antd design表格多选,删除的基础示例
前端·javascript·react.js
rit84324995 分钟前
LTE系统资源分配MATLAB实现示例(基于OFDMA的动态调度)
开发语言·matlab
by__csdn10 分钟前
Vue3响应式系统详解:ref与reactive全面解析
前端·javascript·vue.js·typescript·ecmascript·css3·html5
chilavert31815 分钟前
技术演进中的开发沉思-231 Ajax:页面内容修改
开发语言·前端·javascript
李日灐15 分钟前
C++STL:熟悉vector的底层实现,部分源码解析,迭代器失效和深层次浅拷贝
开发语言·c++
wuk99820 分钟前
基于MATLAB的混合动力汽车(HEV)简单整车模型实现
开发语言·matlab·汽车
偶像你挑的噻20 分钟前
1.Qt-编译器基本知识介绍
开发语言·qt
m0_3761379422 分钟前
DevUI主题系统进阶:CSS-in-JS与暗黑模式无缝切换架构
javascript·css·架构·devui
天天进步201524 分钟前
拒绝“玄学”Bug:C++ 多线程调试指南与 ThreadSanitizer 实战
开发语言
观音山保我别报错25 分钟前
变量作用域
开发语言·python