在React Native渲染文本组件中显示动画数值

6

我无法在Render中显示Animated的值,而且会返回以下错误。

Invariant Violation: Objects are not valid as a React child (found: object with keys {value}). If you meant to render a collection of children, use an array instead.

当然,我可以在控制台中看到Value的值。

constructor(props) {
    super(props);

    this.state={
       progress:0
    }

    this.animatedValue = new Animated.Value(0);

    this.animatedValue.addListener((progress) => {
        this.setState({progress})
    });
}

componentDidMount() {
    this.animate()
}

animate() {
    this.animatedValue.setValue(0);
    Animated.timing(
        this.animatedValue,
        {
            toValue: 1,
            duration: 15000,
            easing: Easing.linear
        }
    ).start()
}

render() {
    return(
        <View>
            <Text> {this.state.progress} </Text>
        </View>
    );

}
2个回答

9
addListener的函数将使用一个带有value键的对象作为参数调用,因此不要使用整个对象设置progress,而是使用value
this.animatedValue.addListener((progress) => {
  this.setState({ progress: progress.value });
});

4
这将导致组件状态的改变,从而引起重新渲染!我说的对吗?如果是,是否存在更好的想法? - Saeed Zhiany
1
避免不必要的重新渲染的一个好方法是在调用 setState 之前依赖于一个条件,例如 if (Math.round(progress.value) !== this.state.progress) - Nick Bull
避免过多的重新渲染的另一种方法是使用节流函数。 - Max

1

如果动画值不经常改变,则Tholle解决方案可以正常工作,因为每次值更改时会导致组件重新渲染(如@saeedZhiany在评论中提到的),这可能会导致性能问题。

对于这些情况,更好的解决方案是使用animatedValue._value属性,类似于这样:

 <Text>
    {Math.round(this.animatedValue._value)}
 </Text>

这样,您可以随时获取实际值,而无需更新组件状态。从而避免性能问题。

1
注意:如果 useNativeDriver: true,则此函数始终返回 0。 - Alexander Sandberg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接