u
This commit is contained in:
1 parent
6277fb2f9e
commit
8ecac0d7dd
270 files changed
+40438
-529
No files matched your search
@@ -0,0 +1,89 @@
|
||||
import React, { useMemo, useRef, useState } from 'react'
|
||||
import { Pressable, Text, View } from 'react-native'
|
||||
import PagerView from 'react-native-pager-view'
|
||||
|
||||
interface TabItem {
|
||||
label: string
|
||||
key: string
|
||||
content?: React.ReactNode
|
||||
}
|
||||
|
||||
interface TabProps {
|
||||
data?: TabItem[]
|
||||
defaultIndex?: number
|
||||
onChange?: (index: number) => void
|
||||
tabBarClass?: string
|
||||
tabItemClass?: string
|
||||
activeTabItemClass?: string
|
||||
}
|
||||
|
||||
export default function Tab({
|
||||
data,
|
||||
defaultIndex = 0,
|
||||
onChange,
|
||||
tabBarClass = 'flex flex-row gap-2 overflow-hidden',
|
||||
tabItemClass = 'items-center justify-center rounded-md px-4 py-2 bg-gray-200',
|
||||
activeTabItemClass = 'items-center justify-center rounded-md px-4 py-2 bg-gray-800',
|
||||
}: TabProps) {
|
||||
const [selectedIndex, setSelectedIndex] = useState(defaultIndex)
|
||||
const pagerRef = useRef<PagerView>(null)
|
||||
|
||||
if (!data || data.length === 0)
|
||||
return null
|
||||
|
||||
// 判断是否至少有一个 tab 含 content
|
||||
const hasContent = useMemo(
|
||||
() => data.some(item => item.content),
|
||||
[data],
|
||||
)
|
||||
|
||||
const handlePress = (index: number) => {
|
||||
setSelectedIndex(index)
|
||||
onChange?.(index)
|
||||
if (hasContent)
|
||||
pagerRef.current?.setPage(index)
|
||||
}
|
||||
|
||||
const onPageSelected = (e: any) => {
|
||||
const index = e.nativeEvent.position
|
||||
setSelectedIndex(index)
|
||||
onChange?.(index)
|
||||
}
|
||||
|
||||
return (
|
||||
<View className="flex-1">
|
||||
{/* tab bar */}
|
||||
<View className={tabBarClass}>
|
||||
{data.map((item, index) => {
|
||||
const isActive = index === selectedIndex
|
||||
return (
|
||||
<Pressable
|
||||
key={item.key}
|
||||
onPress={() => handlePress(index)}
|
||||
className={isActive ? activeTabItemClass : tabItemClass}
|
||||
>
|
||||
<Text className={isActive ? 'text-white' : 'text-gray-700'}>
|
||||
{item.label}
|
||||
</Text>
|
||||
</Pressable>
|
||||
)
|
||||
})}
|
||||
</View>
|
||||
|
||||
{hasContent && (
|
||||
<PagerView
|
||||
ref={pagerRef}
|
||||
style={{ flex: 1, marginTop: 16 }}
|
||||
initialPage={defaultIndex}
|
||||
onPageSelected={onPageSelected}
|
||||
>
|
||||
{data.map(item => (
|
||||
<View key={item.key} style={{ flex: 1 }}>
|
||||
{item.content}
|
||||
</View>
|
||||
))}
|
||||
</PagerView>
|
||||
)}
|
||||
</View>
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user