React Native中如何实现按压组件时使其旋转180度?
实现Pressable按压时图标旋转180度的方案
以下方案针对React Native场景实现:
核心思路
- 借助React Native自带的
Animated库创建可动画的角度状态变量,初始值为0 - 利用Pressable组件的按压回调(
onPressIn/onPressOut)或者内置的pressed状态触发动画 - 通过插值映射把动画值和图标旋转角度绑定,按压时将动画值过渡到180度对应的映射值
- 可根据需求选择松开后恢复原始角度,还是保持旋转状态做切换效果
完整代码示例
import React, { useRef } from 'react'; import { Pressable, Animated, StyleSheet, Easing } from 'react-native'; // 替换为你项目中实际使用的图标库即可 import AntDesign from '@expo/vector-icons/AntDesign'; const RotateIconDemo = () => { // 初始化动画值,0对应初始0度状态 const rotateValue = useRef(new Animated.Value(0)).current; // 按压时触发旋转到180度的动画 const handlePressIn = () => { Animated.timing(rotateValue, { toValue: 1, duration: 250, // 动画时长可自行调整 easing: Easing.inOut(Easing.quad), // 平滑缓动效果 useNativeDriver: true, // 启用原生驱动提升动画流畅度 }).start(); }; // 松开后恢复到0度,如果需要保持旋转状态可删除这个回调 const handlePressOut = () => { Animated.timing(rotateValue, { toValue: 0, duration: 250, easing: Easing.inOut(Easing.quad), useNativeDriver: true, }).start(); }; // 插值映射:把0~1的动画值映射为0~180度的旋转角度 const rotateDegree = rotateValue.interpolate({ inputRange: [0, 1], outputRange: ['0deg', '180deg'] }); const iconAnimatedStyle = { transform: [{ rotate: rotateDegree }] }; return ( <Pressable onPressIn={handlePressIn} onPressOut={handlePressOut} style={styles.pressWrapper} > {/* 给图标套上Animated.View绑定动画样式,图标支持透传样式的话也可以直接绑定给图标 */} <Animated.View style={iconAnimatedStyle}> <AntDesign name="down" size={24} color="#333" /> </Animated.View> </Pressable> ); }; const styles = StyleSheet.create({ pressWrapper: { padding: 10, } }); export default RotateIconDemo;
常见自定义调整
- 如果需要点击一次就永久切换旋转状态(比如展开收起箭头),可以删除
onPressOut回调,在onPress事件里根据当前状态切换toValue的参数即可 - 如果不需要过渡动画,直接切换角度,可以不用
Animated库,直接用state存旋转角度,Pressable的子函数接收pressed参数动态绑定transform样式即可
内容的提问来源于stack exchange,提问作者Hora
相关产品推荐
相关产品推荐

