4

我正在研究如何在本机反应中为颜色设置动画并遵循本教程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')

4

1 回答 1

3

生命componentDidMount周期方法仅在第一个render. 因此this.animatedValue,当组件第一次挂载时将是未定义的。

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

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

  //...
}

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

于 2018-02-08T09:36:29.280 回答