gpt4 book ai didi

javascript - Undefined 不是对象 animated.interpolate react native

转载 作者:行者123 更新时间:2023-11-30 11:24:09 26 4
gpt4 key购买 nike

我正在研究如何在 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 方法。

关于javascript - Undefined 不是对象 animated.interpolate react native,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48680452/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com