当 pin 不正确时反应本机摇动 pin 视图

React native shaking pin view when pin incorrect

我正在尝试实现一项功能,当用户输入错误的密码时,4 个小圆圈会左右摇动。

我创建了一个动画组件来测试我的代码并且它正在运行,但现在我的问题是如何仅在密码不正确时应用它?

目前,当我输入错误的密码时,没有任何反应。我期望的是视图水平移动。


const shake = new Animated.Value(0.5);

const [subtle,setSubtle]=useState(true);
const [auto,setAuto]=useState(false);

const translateXAnim = shake.interpolate({
  inputRange: [0, 1],
  outputRange: [subtle ? -8 : -16, subtle ? 8 : 16],
});

const getAnimationStyles = () => ({
  transform: [
    {
      translateX: translateXAnim,
    },
  ],
});

const runAnimation = () => {
  Animated.sequence([
    Animated.timing(shake, {
      delay: 300,
      toValue: 1,
      duration: subtle ? 300 : 200,
      easing: Easing.out(Easing.sin),
      useNativeDriver: true,
    }),
    Animated.timing(shake, {
      toValue: 0,
      duration: subtle ? 200 : 100,
      easing: Easing.out(Easing.sin),
      useNativeDriver: true,
    }),
    Animated.timing(shake, {
      toValue: 1,
      duration: subtle ? 200 : 100,
      easing: Easing.out(Easing.sin),
      useNativeDriver: true,
    }),
    Animated.timing(shake, {
      toValue: 0,
      duration: subtle ? 200 : 100,
      easing: Easing.out(Easing.sin),
      useNativeDriver: true,
    }),
    Animated.timing(shake, {
      toValue: 0.5,
      duration: subtle ? 300 : 200,
      easing: Easing.out(Easing.sin),
      useNativeDriver: true,
    }),
  ]).start(() => {
    if (auto) runAnimation();
  });
};

const stopAnimation = () => {
 shake.stopAnimation();
};

const handleConfirm = async()=>{  
      const result = await authApi();
  
      if(!result.ok) {
      setAuto(true)
      setSubtle(true)
      runAnimation()
      stopAnimation()

      return setLoginFailed(true);
      }
  
      setLoginFailed(false);
      };

return(

<Animated.View style={[getAnimationStyles()]}>

        <View style={styles.circleBlock}> 
         {
           password.map(p=>{
             let style =p != ''?styles.circleFill
               : styles.circle
            
            return <View style={style}></View>
           })
         }
          </View>

          </Animated.View>

问题是您没有将 useRef() 用于

const shake = new Animated.Value(0.5);

应该是

const shake = useRef(new Animated.Value(0.5)).current;

useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.

https://reactjs.org/docs/hooks-reference.html#useref

为动画抖动效果制作了具有相同输入和输出范围值的单独的 expo 小吃。检查一下。

博览会:https://snack.expo.io/@klakshman318/runshakeanimation