调用动画函数来对按钮进行动画处理会导致意外行为



我有一个文本字段,当长度大于 1 时,底部会出现一个按钮。 如果为零,则按钮消失。它使用 componentWillReceiveProps 来检查按钮是否从父级传递的 props 中"可见"。

这是动画功能:

animateButton(toValue, speed) {
if (this.state.isMidAnimation) {
return;
}
this.setState({ isMidAnimation: true }, () => {
Animated.timing(this.state.animatedBottomOffset, {
toValue,
duration: speed,
delay: 0,
}).start(() => {
this.setState({ isMidAnimation: false });
});
});
}

它是在componentWillReceiveProps中触发的,它的动画,取决于可见与否,按按钮的高度上升,或按高度向下:

componentWillReceiveProps(nextProps) {
if (nextProps.isVisible !== this.props.isVisible) {
const currentOffset = this.state.animatedBottomOffset._value;
const offset = nextProps.isVisible ? this.props.height : - this.props.height;
this.animateButton(offset + currentOffset, BUTTON_TOGGLING_SPEED);
}
}

如果我让动画完成,这将按预期运行,并且看起来很棒。问题是,当我在文本输入字段长度 0 和 1 之间快速来回切换时,按钮不是停留在"开"或"关"位置,而是开始让它的最终位置越来越高,或者越来越低,直到它离开屏幕。

我怀疑这与this.state.animatedBottomOffset._value有关,但这是我需要设置的,因为它是组件安装时键盘的高度,并且状态检查是否isMidAnimation似乎没有帮助。

不应该回到这里:

if (this.state.isMidAnimation) {
return;
}

应保留正在进行的动画的引用。停止正在进行的动画,并在此 if 语句中启动一个新动画。

最新更新