首页 > 解决方案 > 如何在本机反应中添加对 Animated.sequence 的函数调用

问题描述

我的屏幕中间有一个按钮。onScroll 我希望按钮缩小到 0 以消失,然后缩小到 1 以重新出现在屏幕底部的新位置。我希望能够在缩小和放大动画之间调用 setState (控制按钮的位置)。类似于下面的代码。知道在这两个动画之间添加函数调用的最佳方法吗?或者更好的方式来做到这一点?

animateScale = () => {
 return (
   Animated.sequence([
     Animated.timing(
       this.state.scale,
       {
         toValue: 0,
         duration: 300
       }
     ),
     this.setState({ positionBottom: true }),
     Animated.timing(
       this.state.scale,
       {
         toValue: 1,
         duration: 300
       }
     )
   ]).start()
 )

}

标签: react-nativeanimation

解决方案


经过更多研究,我发现 answer.start() 采用回调函数,如下所示:

Animate.spring 完成后调用函数

这是我的最终解决方案:

    export default class MyAnimatedScreen extends PureComponent {
    state = {
     scale: new Animated.Value(1),
     positionUp: true,
     animating: false
    }

    animationStep = (toValue, callback) => () => (
     Animated.timing(this.state.scale, {
       toValue,
       duration: 200
     }).start(callback)
    )

    beginAnimation = (value) => {
     if (this.state.animating) return

     this.setState({ animating: true }, this.animationStep(0, () => {
      this.setState({ positionUp: value, animating: false }, 
      this.animationStep(1))
     }))
    }

    handleScrollAnim = ({ nativeEvent }) => {
     const { y } = nativeEvent.contentOffset

     if (y < 10) {
      if (!this.state.positionUp) {
        this.beginAnimation(true)
      }
    } else if (this.state.positionUp) {
      this.beginAnimation(false)
    }
  }

  render() {
    return (
      <View>
        <Animated.View
          style={[
            styles.buttonWrapper,
            { transform: [{ scale: this.state.scale }] },
            this.state.positionUp ? styles.buttonAlignTop : 
            styles.buttonAlignBottom
          ]}
        >
          <ButtonCircle />
        </Animated.View>
        <ScrollView
          onScroll={this.handleScrollAnim}
        >
        // scroll stuff here
        </ScrollView>
      </View>
     )
    }
  }

推荐阅读