未定义不是对象 animated.interpolate 反应本机

Undefined is not an object animated.interpolate react native

我正在研究如何在 React Native 中设置动画颜色并按照本教程进行操作 https://codedaily.io/screencasts/8/Animate-Colors-with-React-Native-Interpolate

我所做的只是先 运行 react-native init 然后用

替换我 App.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')

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

您可以在组件上将动画值声明为一个实例 属性,这样它在组件首次创建时就可用。

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

  //...
}

此外,您不能像此处那样定义多个 componentDidMount 方法。