1

我正在尝试实现一个功能,当用户输入错误的密码时,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>
4

1 回答 1

1

问题是你没有useRef()使用

const shake = new Animated.Value(0.5);

应该

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

useRef 返回一个可变 ref 对象,其 .current 属性初始化为传递的参数 (initialValue)。返回的对象将在组件的整个生命周期内持续存在。

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

在此处输入图像描述

为动画抖动效果制作了具有相同输入和输出范围值的单独博览会小吃。一探究竟。

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

于 2021-04-19T11:20:49.803 回答