简体   繁体   English

在 React-Native 中的 animation 期间禁用按钮

[英]Disable the button during the animation in React-Native

I'm trying to create an app that starts animation after a button click and disables the button while the animation is running.我正在尝试创建一个应用程序,该应用程序在单击按钮后启动 animation 并在 animation 运行时禁用该按钮。 I want to be able to use it multiple times by pressing the button, disabling it, running animation, then reenabling it.我希望能够通过按下按钮多次使用它,禁用它,运行 animation,然后重新启用它。 So far, I have a button that gets disabled when I press it and then after that I run an animation (blue square moves to the right and then back to starting position), or at least that's what I was hoping for.到目前为止,我有一个按钮,当我按下它时会被禁用,然后我运行 animation(蓝色方块向右移动,然后回到起始位置),或者至少这是我所希望的。 The reality of the situation is that when a button is pressed, it becomes disabled but no animation occurs.实际情况是,当按下按钮时,它会变为禁用状态,但不会发生 animation。 Upon further investigation, I found that the problem results from the use of setState while the animation is active.经过进一步调查,我发现问题是由于在 animation 处于活动状态时使用setState造成的。 For example, if you setState while the animation is running, the animation will just stop.例如,如果您在setState运行时设置状态,则 animation 将停止。 However, I don't understand why setting state before animation begins doesn't work either.但是,我不明白为什么在 animation 开始之前设置 state 也不起作用。 I'm using Animated.View and this is my code:我正在使用Animated.View ,这是我的代码:

import React, { useState } from 'react'
import { Animated, View, Button } from 'react-native';

export default function App() {
  const [dis,setDis] = useState(false)
  const animatedMargin = new Animated.Value(0);
  const slideAnimation = () => {
    Animated.timing(animatedMargin, { //go right
      toValue: 200,
      duration: 1000,
      useNativeDriver: false 
    }).start()
    setTimeout(() => {
      Animated.timing(animatedMargin, { //return left
        toValue: 0,
        duration: 1000,
        useNativeDriver: false 
      }).start()
    }, 1000);
    setTimeout(() => { setDis(false) }, 2000); //enable button
  }
  return (
    <View style={{ marginTop:50 }}>
      <Animated.View style={{ left: animatedMargin }}>
        <View style={{ backgroundColor:'#00f', height:50, width:50 }}/>
      </Animated.View>
        <Button title='go' disabled={dis}
          onPress={()=>{
            setDis(true),
            slideAnimation()
          }}
        ></Button>
    </View>
  );
}


If I don't use parts of code for disabling and enabling buttons, the animation works fine.如果我不使用部分代码来禁用和启用按钮,animation 工作正常。

Seems that problem is animated value here.似乎问题是这里的动画价值。 Just wrap it by useRef like so:只需像这样用useRef包装它:

const animatedMargin = React.useRef(new Animated.Value(0)).current;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM