我尝试实现滑动条并将滑动动画绑定到TouchableOpacity
我将参数初始化为sliderPosition: new Animated.Value(0)
onPress函数是:

  onPress: function(event){
    Animated.timing(this.state.sliderPosition, {
      toValue: 202.5,
      duration: 100,
      easing: Easing.linear,
    }).start();
  },


我一直收到这个错误

[tid:com.facebook.react.RCTExceptionsManagerQueue] Unhandled JS Exception: singleValue.stopTracking is not a function. (In 'singleValue.stopTracking()', 'singleValue.stopTracking' is undefined)

滑块的布局为:

    <View style = {styles.sliderContainer}>
      <Animated.View style = {[styles.slider, {marginLeft:this.state.sliderPosition}]}>
      </Animated.View>
    </View>


样式:

sliderContainer: {
  position: 'absolute',
  top: 138,
  left: 0,
  right: 0,
  height: 5,
  backgroundColor: '#E15668',
  shadowRadius: 1,
  shadowOpacity: 0.5,
  shadowColor: 'gray',
  shadowOffset: {width: 0, height: 2},
  opacity: 0.9
},
slider: {
  marginTop: 0,
  backgroundColor: '#FCC31B',
  width: 120,
  height: 5,
},


我做错什么了吗?

最佳答案

您确定状态的sliderPosition属性仍然是Animated.Value的实例吗?您遇到的那个错误说明了这个问题。这是一个使用您的代码段的完整示例,它可以按预期工作。尝试一下,如果该片段不能帮助您解决问题,请发布更多周围的代码,以提供更多上下文:

import React from 'react';
import {
  Animated,
  AppRegistry,
  Easing,
  StyleSheet,
  Text,
  TouchableOpacity,
  View
} from 'react-native';

class MyApp extends React.Component {
  constructor(props) {
    super(props);

    this.onPress = this.onPress.bind(this);

    this.state = {
      sliderPosition: new Animated.Value(0)
    }
  }

  onPress(event){
    Animated.timing(this.state.sliderPosition, {
      toValue: 202.5,
      duration: 100,
      easing: Easing.linear,
    }).start();
  }

  render() {
    return (
      <View style={styles.container}>
        <TouchableOpacity onPress={this.onPress}>
          <Text>Animate It</Text>
        </TouchableOpacity>

        <View style = {styles.sliderContainer}>
          <Animated.View style = {[styles.slider, {marginLeft:this.state.sliderPosition}]}>
          </Animated.View>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },

  sliderContainer: {
    position: 'absolute',
    top: 138,
    left: 0,
    right: 0,
    height: 5,
    backgroundColor: '#E15668',
    shadowRadius: 1,
    shadowOpacity: 0.5,
    shadowColor: 'gray',
    shadowOffset: {width: 0, height: 2},
    opacity: 0.9
  },

  slider: {
    marginTop: 0,
    backgroundColor: '#FCC31B',
    width: 120,
    height: 5,
  }
});

AppRegistry.registerComponent('MyApp', () => MyApp);

07-27 13:40