UNPKG

@uiw/react-native

Version:
85 lines 2.77 kB
import React, { useRef, useEffect, useState } from 'react'; import { StyleSheet, SafeAreaView, ScrollView, View, Dimensions } from 'react-native'; import Item from './TabsItem'; function Tabs(props) { const { style, children, onChange, activeColor, value, defaultColor = '#035bb6' } = props; const scrollViewRef = useRef(null); const [scrollViewWidth, setScrollViewWidth] = useState(Dimensions.get('window').width); useEffect(() => { const handleResize = () => { setScrollViewWidth(Dimensions.get('window').width); }; Dimensions.addEventListener('change', handleResize); return () => { Dimensions.removeEventListener('change', handleResize); }; }, []); if (!children) { return null; } if (Array.isArray(children) && children.find(item => typeof item.type !== 'function' || !item.type.prototype.isclxItem)) { console.error('Tags component child element must be TagsItem'); throw new Error('Child elements of tabs components must be Tabs.Item'); } if (!Array.isArray(children) && typeof children.type !== 'function' || 'type' in children && !children.type.prototype.isclxItem) { console.error('Tags component child element must be TagsItem'); throw new Error('Child elements of tabs components must be Tabs.Item'); } const handleTabChange = tabIndex => { scrollViewRef.current?.scrollTo({ x: tabIndex * 50, y: 0, animated: true }); onChange && onChange(tabIndex); }; return <SafeAreaView> <View style={[styles.TabsContainer, style]}> <ScrollView ref={scrollViewRef} horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={{ justifyContent: 'space-between', alignItems: 'center' }} onContentSizeChange={() => { setScrollViewWidth(Dimensions.get('window').width); }}> {children && React.Children.toArray(children).map((child, index) => { if (!React.isValidElement(child)) { return; } return React.cloneElement(child, { ...child.props, ...{ value: value, onChange: handleTabChange, index: index, activeColor: activeColor, defaultColor: defaultColor } }); })} </ScrollView> </View> {children && React.Children.toArray(children).map((child, index) => { if (!React.isValidElement(child)) { return; } if (value === index) { return child.props?.children; } })} </SafeAreaView>; } const styles = StyleSheet.create({ TabsContainer: { backgroundColor: '#fff', paddingVertical: 15 } }); Tabs.Item = Item; export default Tabs;