【问题标题】:Undefined is not an object animated.interpolate react native未定义不是一个对象动画。插值反应原生
【发布时间】:2018-02-08 08:04:16
【问题描述】:

我正在研究如何在 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'重复。

标签: javascript react-native react-animated


【解决方案1】:

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

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

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

  //...
}

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

【讨论】:

  • 第一个 componentDidMount 应该是 componentWillMount 但我猜它也在第一个 render 之后运行?无论如何,感谢您的帮助,现在效果很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-11
  • 2018-10-03
相关资源
最近更新 更多