@uiw/react-native
Version:
UIW for React Native
61 lines • 1.61 kB
JavaScript
import React, { useState } from 'react';
import { Text } from 'react-native';
import ButtonGroup from '../ButtonGroup';
import Button from '../Button';
export default function SegmentedControl(props) {
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: '#fff',
unactived: props.color ?? '#108ee9'
},
...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 = otherProps.color;
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,
color: '#108ee9'
};