UNPKG

@uiw/react-native

Version:
50 lines (49 loc) 1.98 kB
import React, { useState } from 'react'; import { Text } from 'react-native'; import ButtonGroup from '../ButtonGroup'; import Button from '../Button'; import { useTheme } from '@shopify/restyle'; export default function SegmentedControl(props) { const theme = useTheme(); const [state, setState] = useState({ selectedIndex: props.selectedIndex || 0, }); const handlePress = (label, selectedIndex) => { setState({ selectedIndex }); const { onValueChange } = props; onValueChange && onValueChange(label, selectedIndex); return undefined; }; const { value, selectedIndex, renderItem, textColor = { actived: theme.colors.text_active || '#fff', unactived: props.color ?? (theme.colors.primary_background || '#3578e5'), }, colors = props.color || theme.colors.primary_background || '#3578e5', ...otherProps } = props; return (<ButtonGroup {...otherProps}> {value && value.map((label, key) => { const styl = {}; const textStyle = {}; let textStyleColor = textColor.actived; if (state.selectedIndex !== key + 1) { styl.backgroundColor = '#fff'; textStyle.color = colors; textStyleColor = textColor.unactived; } const props = { type: 'primary', style: [styl, otherProps.textStyle], textStyle: [textStyle], onPress: () => handlePress(label, key + 1), }; if (renderItem) { return renderItem(label, key + 1, props); } return React.cloneElement(<Button key={key}/>, { ...props }, <Text style={{ color: textStyleColor }}>{label}</Text>); })} </ButtonGroup>); } SegmentedControl.defaultProps = { value: [], size: 'small', selectedIndex: 0, };