如何在React Native中按下一个组件并使其旋转180度?

Hor*_*ora 5 animation react-native

我有一个可压组件,里面有一个图标。我想按下它并旋转180度,我该怎么做?

car*_*eld 7

因此,要做到这一点,您必须使用react-native 中的Animated 库。您可以在其中制作动画值并创建函数来更新它们。这是您想要的完整示例(https://snack.expo.dev/@heytony01/grumpy-pretzel),下面是解释。

首先导入库并制作一个动画值

import { Text, View, StyleSheet,Animated,TouchableWithoutFeedback } from 'react-native';

const spinValue = React.useState(new Animated.Value(0))[0]; // Makes animated value
Run Code Online (Sandbox Code Playgroud)

接下来定义函数来更改值


 // When button is pressed in, make spinValue go through and up to 1
 const onPressIn = () => {
     Animated.spring(spinValue, {
         toValue: 1,
         useNativeDriver: true,
     }).start();
 };

 // When button is pressed out, make spinValue go through and down to 0
 const onPressOut = () => {
     Animated.spring(spinValue, {
         toValue: 0,
         useNativeDriver: true,
     }).start();
 };
Run Code Online (Sandbox Code Playgroud)

棘手的部分是,为了在反应本机中旋转,您需要传递“0deg”或“12deg”等。

<View style={{
        transform: [
          { rotate: "45deg" },
        ]
      }}>
 </View>
Run Code Online (Sandbox Code Playgroud)

所以你要做的就是将动画值插入“0deg”到“360deg”

// spinDeg will be between '0deg' and '360deg' based on what spinValue is 
const spinDeg = spinValue.interpolate({
      useNativeDriver: true,
      inputRange: [0, 1],
      outputRange: ['0deg', '360deg']
  })
Run Code Online (Sandbox Code Playgroud)

最后,将 spinDeg 传递到按钮中,完成

 // The animated style for scaling the button within the Animated.View
    const animatedScaleStyle = {
        transform: [{rotate: spinDeg}]
    };

    return (
      <View style={{flex:1,justifyContent:"center",alignItems:"center"}}>
          <TouchableWithoutFeedback
             
              onPress={()=>{}}
              onPressIn={onPressIn}
              onPressOut={onPressOut}
          >
          <View style={{justifyContent:"center",alignItems:"center",backgroundColor:"lightgray",padding:15,borderRadius:20}}>
              <Text>PRESS ME</Text>
              <Animated.View style={[styles.iconContainer, animatedScaleStyle]}>
                        <Ionicons name="md-checkmark-circle" size={32} color="green" />
              </Animated.View>
            </View>
        </TouchableWithoutFeedback>
      </View>
    );
Run Code Online (Sandbox Code Playgroud)