代码之家  ›  专栏  ›  技术社区  ›  rivaldragon

未定义不是已设置动画的对象。插入反应本机

  •  4
  • rivaldragon  · 技术社区  · 8 年前

    我正在研究如何在react native中设置颜色动画,并遵循了本教程 https://codedaily.io/screencasts/8/Animate-Colors-with-React-Native-Interpolate

    我所做的就是第一次跑步 react-native init 然后替换我的应用程序中的代码。js与此

    import { StyleSheet, View, Text, Animated } from 'react-native';
    import React, { Component } from 'react';
    
    export default class App extends Component {
    
    componentDidMount() {
      this.animatedValue = new Animated.Value(0);
    }
    
    componentDidMount() {
     Animated.timing(this.animatedValue, {
      toValue: 150,
      duration: 1500
    }).start();
    }
    
        render() {
        const interpolateColor = this.animatedValue.interpolate({
          inputRange: [0, 150],
          outputRange: ['rgb(0,0,0)', 'rga(51,250,170)']
        });
    
        const animatedStyle = {
          backgroundColor: interpolateColor
        }
        return (
          <Animated.View style={[{ width: 50, height: 50 }, animatedStyle]} />
        );
    }
    }
    

    然后运行 react-native run-android

    现在我一直在 TypeError:undefined is not an object(evaluating 'this.animatedValue.interpolate')

    1 回复  |  直到 7 年前
        1
  •  3
  •   jevakallio    8 年前

    这个 componentDidMount 生命周期方法仅在第一个 render . 因此 this.animatedValue 将在组件首次安装时未定义。

    可以将动画值声明为组件上的实例属性,以便从首次创建组件时起即可使用。

    export default class App extends Component {
      animatedValue = new Animated.Value(0)
    
      //...
    }
    

    此外,您不能定义多个 组件安装 方法。