在 React-Native 的动画期间禁用按钮
Disable the button during the animation in React-Native
我正在尝试创建一个在单击按钮后启动动画并在动画 运行 期间禁用按钮的应用。我希望能够通过按下按钮多次使用它,禁用它,运行设置动画,然后重新启用它。到目前为止,我有一个按钮,当我按下它时它会被禁用,然后我 运行 一个动画(蓝色方块向右移动然后回到起始位置),或者至少这是我所希望的.实际情况是,当按下按钮时,它会被禁用但不会出现动画。经过进一步调查,我发现问题是由于在动画处于活动状态时使用 setState
引起的。例如,如果您 setState
而动画正在 运行ning,则动画将停止。但是,我不明白为什么在动画开始之前设置状态也不起作用。我正在使用 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>
);
}
如果我不使用部分代码来禁用和启用按钮,动画效果很好。
看来问题是这里的动画值。像这样用 useRef
包裹它:
const animatedMargin = React.useRef(new Animated.Value(0)).current;
例如,如果您的动画值在 500 毫秒内从 0 变为 1,当您更改状态(重新渲染组件)时,将创建一个新实例并丢失当前进度,这就是您需要包装它的原因通过 useRef
挂钩仅创建一次实例。
我正在尝试创建一个在单击按钮后启动动画并在动画 运行 期间禁用按钮的应用。我希望能够通过按下按钮多次使用它,禁用它,运行设置动画,然后重新启用它。到目前为止,我有一个按钮,当我按下它时它会被禁用,然后我 运行 一个动画(蓝色方块向右移动然后回到起始位置),或者至少这是我所希望的.实际情况是,当按下按钮时,它会被禁用但不会出现动画。经过进一步调查,我发现问题是由于在动画处于活动状态时使用 setState
引起的。例如,如果您 setState
而动画正在 运行ning,则动画将停止。但是,我不明白为什么在动画开始之前设置状态也不起作用。我正在使用 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>
);
}
如果我不使用部分代码来禁用和启用按钮,动画效果很好。
看来问题是这里的动画值。像这样用 useRef
包裹它:
const animatedMargin = React.useRef(new Animated.Value(0)).current;
例如,如果您的动画值在 500 毫秒内从 0 变为 1,当您更改状态(重新渲染组件)时,将创建一个新实例并丢失当前进度,这就是您需要包装它的原因通过 useRef
挂钩仅创建一次实例。