动画持续时间问题



我尝试对视图进行动画处理以隐藏和显示它。 持续时间可以打开它(500(,但是当我关闭它时它不起作用,持续时间不被遵守(它直接关闭(。

这是我的代码:

const {height, width} = Dimensions.get('window');
const [initialHeight] = useState(new Animated.Value(0));
useEffect(() => {
if (state === true) {
Animated.timing(initialHeight, {
toValue: height - 400,
duration: 500,
}).start();
} else {
Animated.timing(initialHeight, {
toValue: 0,
duration: 500,
}).start();
}
}, [height, initialHeight, state]);
...
<Animated.View style={{height: initialHeight, paddingVertical: 12}}>

我错过了什么?

---编辑

我进行了此更改,但它没有解决问题:

const [initialHeight, setInitialHeight] = useState(new Animated.Value(0));
useEffect(() => {
if (state === true) {
Animated.timing(initialHeight, {
toValue: height - 400,
duration: 500,
}).start(() => {
setInitialHeight(new Animated.Value(height - 400));
});
} else {
Animated.timing(initialHeight, {
toValue: 0,
duration: 500,
}).start(() => {
setInitialHeight(new Animated.Value(0));
});
}
}, [height, initialHeight, state]);

您可以使用 useRef 来存储您的动画值:

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

而且您不必手动更新它:

useEffect(() => {
if (state) { //If state is a boolean, you don't need to do === true
Animated.timing(initialHeight, {
toValue: height - 400,
duration: 500,
}).start();
} else {
Animated.timing(initialHeight, {
toValue: 0,
duration: 500,
}).start();
}
}, [state]); // If you want to initiate your animation only on this prop change

不要忘记检查height - 400的结果。每个动画,从height - 4000和反转需要500毫秒。

好吧,我终于找到了问题所在,并找到了解决方案。每次道具状态更改时,组件都会完全重新渲染。因此,我将父组件中的状态变量更改为这样的对象:{firstRender: true, open: false},并根据这些参数更改了初始高度的值。它就像一个魅力! 我确信有更好的解决方案,但是在搜索了几个小时后,我找不到任何解决方案。

最新更新