【问题标题】:Display Animated Value in React Native Render Text Component在 React Native 渲染文本组件中显示动画值
【发布时间】:2018-07-03 18:25:58
【问题描述】:

我无法在 Render 上显示 Animated 的值并返回此错误。

Invariant Violation:对象作为 React 子级无效(发现:带有键 {value} 的对象)。如果您打算渲染一组子项,请改用数组。

当然,我在console中看到了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>
    );

}

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:

    赋予addListener 的函数将使用带有value 键的对象作为参数调用,因此不要使用整个对象设置progress,而是使用value

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

    【讨论】:

    • 这会导致组件状态发生变化,所以重新渲染!对吗?如果是,还有更好的主意吗?
    • 避免不必要的重新渲染的一个好方法是在调用setState之前依赖一个条件,例如if (Math.round(progress.value) !== this.state.progress)
    【解决方案2】:

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

    对于这些情况,更好的解决方案是使用animatedValue._value 属性,如下所示:

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

    通过这种方式,您可以随时获得真正的价值,而无需更新组件状态。从而避免性能问题。

    【讨论】:

    • 注意:如果useNativeDriver: true这将始终返回0。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-14
    • 2016-06-13
    • 1970-01-01
    • 2021-10-26
    • 2022-10-08
    • 1970-01-01
    相关资源
    最近更新 更多