【发布时间】:2023-04-04 10:50:01
【问题描述】:
问题:
目前,我正在与useEffect Hook 和Animated.timing 一起努力。不知何故,没有显示反向动画。切换只是跳回来(见下面的 gif)。令人困惑的是,动画回调被成功调用。
想要的行为:当活动道具改变时,滑块应该来回平滑地动画。
代码
滑块:
const Slider = ({sliderWidth, circleHeight, active, onToggle}) => {
const transformX = new Animated.Value(0);
React.useEffect(() => {
console.log('only run when active changed', transformX);
const value = active ? sliderWidth-circleHeight: 0;
console.log('value', value);
Animated.timing(transformX, {
toValue: value,
duration: 500,
useNativeDriver: true
}).start(() => console.log('animation done'));
}, [active, transformX, sliderWidth, circleHeight]);
return (
<View style={{position: 'absolute',width: sliderWidth+10, backgroundColor: 'white', borderBottomLeftRadius: 8, borderBottomRightRadius: 8, flexDirection: 'column', alignItems: 'center'}}>
<View style={{width: sliderWidth, borderRadius: sliderWidth/2, borderWidth: 1, height: circleHeight,justifyContent: 'center', alignItems: 'center', marginTop: 8, marginBottom: 8, backgroundColor: 'white'}}>
<Text style={{fontSize: 11}}> {active ? "Pickup" : "Delivery"} </Text>
<TouchableOpacity onPress={onToggle} style={{position: 'absolute', left:0, transform: [{translateX: transformX}]}}>
<View style={{height: circleHeight-2, width: circleHeight-2, borderRadius: circleHeight/2-1, backgroundColor: 'orange' }} />
</TouchableOpacity>
</View>
</View>
);
};
应用:
export default function App() {
const sliderWidth = WIDTH/3;
const circleHeight = 30;
const [active, setActive] = React.useState(0);
return (
<View style={styles.container}>
<Slider sliderWidth={sliderWidth} circleHeight={circleHeight} onToggle={() => setActive(!active)} active={active}/>
</View>
);
}
小吃
【问题讨论】:
标签: react-native animation react-hooks use-effect