diff --git a/js/SegmentedControl.js b/js/SegmentedControl.js index bcfa5d3d..77fbe61e 100644 --- a/js/SegmentedControl.js +++ b/js/SegmentedControl.js @@ -5,7 +5,7 @@ 'use strict'; import * as React from 'react'; -import {StyleSheet, View} from 'react-native'; +import {Animated, Easing, StyleSheet, View} from 'react-native'; import {SegmentedControlTab} from './SegmentedControlTab'; import type {SegmentedControlProps} from './types'; @@ -27,6 +27,9 @@ const SegmentedControl = ({ backgroundColor, fontSize, }: SegmentedControlProps) => { + const [segmentWidth, setSegmentWidth] = React.useState(0); + const animation = React.useRef(new Animated.Value(0)).current; + const handleChange = (index: number) => { // mocks iOS's nativeEvent const event: any = { @@ -38,6 +41,18 @@ const SegmentedControl = ({ onChange && onChange(event); onValueChange && onValueChange(values[index]); }; + + React.useEffect(() => { + if (animation && segmentWidth) { + Animated.timing(animation, { + toValue: segmentWidth * (selectedIndex || 0), + duration: 300, + easing: Easing.out(Easing.quad), + useNativeDriver: true, + }).start(); + } + }, [animation, segmentWidth, selectedIndex]); + return ( + ]} + onLayout={({ + nativeEvent: { + layout: {width}, + }, + }) => { + const newSegmentWidth = values.length ? width / values.length : 0; + if (newSegmentWidth !== segmentWidth) { + animation.setValue(newSegmentWidth * (selectedIndex || 0)); + setSegmentWidth(newSegmentWidth); + } + }}> + {selectedIndex != null && segmentWidth ? ( + + ) : null} {values && values.map((value, index) => { return ( @@ -70,6 +108,8 @@ const SegmentedControl = ({ const styles = StyleSheet.create({ default: { + overflow: 'hidden', + position: 'relative', flexDirection: 'row', justifyContent: 'space-evenly', alignContent: 'center', @@ -80,6 +120,14 @@ const styles = StyleSheet.create({ disabled: { opacity: 0.4, }, + slider: { + position: 'absolute', + borderRadius: 5, + top: 1, + bottom: 1, + right: 1, + left: 1, + }, }); export default SegmentedControl; diff --git a/js/SegmentedControlTab.js b/js/SegmentedControlTab.js index 3c878d0f..aa770bf8 100644 --- a/js/SegmentedControlTab.js +++ b/js/SegmentedControlTab.js @@ -42,22 +42,12 @@ export const SegmentedControlTab = ({ }; const color = getColor(); - const getBackgroundColor = () => { - if (selected && tintColor) { - return tintColor; - } - return 'white'; - }; return ( - +