首页 > 解决方案 > 轻敲一个移动的动画对象

问题描述

我想编写一个简单的应用程序,其中对象在屏幕上移动,目标是点击它们。我将动画 API 包含在componentDidMount

Animated.timing(
  this.state.fadeAnim,
  {
    toValue: 1,
    duration: 10000,
  }
).start();     

然后我会在我的 React 组件的render方法中设置样式:

<TouchableHighlight onPress={this.setText} >
  <Animated.View style={{
    opacity: this.state.fadeAnim, // Binds directly
    transform: [{
      translateY: this.state.fadeAnim.interpolate({
        inputRange: [0, 1],
        outputRange: [500, 0]  // 0 : 150, 0.5 : 75, 1 : 0
      }),
    }],
  }}>
    <Image source={pic} style={{width: 193, height: 110, display: display}}/>
  </Animated.View>    
</TouchableHighlight>

问题是图像在移动时对点击没有反应。当我点击它的最终目的地时它确实如此,但它在移动时所处的位置。你们能帮我解决这个问题吗?或者 React-Native 不是这类应用程序的最佳工具,我应该转向原生开发吗?

标签: react-native

解决方案


首先,我们可以在这里使用原生驱动

Animated.timing(
  this.state.fadeAnim,
  {
    toValue: 1,
    duration: 10000,
    useNativeDriver: true
  }
).start();     

并且transform样式应该被赋予TouchableHighlight. 问题是Image正在移动,但按钮不是,因此不会触发 onClick。

  <Animated.View style={{
    opacity: this.state.fadeAnim, // Binds directly
    transform: [{
      translateY: this.state.fadeAnim.interpolate({
        inputRange: [0, 1],
        outputRange: [500, 0]  // 0 : 150, 0.5 : 75, 1 : 0
      }),
    }],
  }}>
    <TouchableHighlight onPress={this.setText} >
      <Image source={pic} style={{width: 193, height: 110, display: display}}/>
    </TouchableHighlight>
  </Animated.View> 

这应该有效。也反应原生应该很好。


推荐阅读