You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中Animated绑定ScrollView报onScroll不是函数及scrollY节点异常

React Native Animated滚动监听问题修复方案

1. 报错「this.props.onScroll is not a function」的修复

原因

Animated.event生成的事件处理器只能绑定到Animated封装的原生组件上,你代码里用的普通ScrollView不识别Animated事件对象,因此抛出该错误。

解决方案

将普通ScrollView替换为Animated.ScrollView即可。

2. scrollY被判定为空节点的问题说明

原因

你看到的空判定是误判,从控制台输出可以明确scrollY是正常的Animated.Value实例:存在__nodeID、_value为0、__children数组也有绑定的动画算子。触发误判的常见原因有两个:

  • 你把scrollY声明在了组件渲染函数内部,每次组件重渲染都会生成新的Animated.Value实例,之前绑定的旧实例被释放后就会被识别为空
  • 你用了if(!scrollY)这类真值校验,部分框架内部判断Animated节点时误读了__memoizedValue: {"": null}这个内部缓存字段,错把正常实例判定为空

解决方案

  • 缓存Animated.Value实例:函数组件用useRef包裹,类组件放到constructor中声明,避免重渲染生成新实例
    示例:
    // 函数组件写法
    const scrollY = useRef(new Animated.Value(0)).current
    
  • 校验Animated节点时用scrollY instanceof Animated.Value代替普通真值判断

完整可运行示例代码

import React, { useRef } from 'react';
import { Animated, Text, View } from 'react-native';

export default function ScrollDemo() {
  const scrollY = useRef(new Animated.Value(0)).current;
  const onScroll = Animated.event(
    [{ nativeEvent: { contentOffset: { y: scrollY } } }],
    {
      listener: (event) => console.log('滚动偏移量', event.nativeEvent.contentOffset.y),
      useNativeDriver: false,
    }
  );

  return (
    <Animated.ScrollView
      scrollEventThrottle={16}
      onScroll={onScroll}
      style={{ flex: 1 }}
    >
      {Array(20).fill(0).map((_, i) => (
        <View key={i} style={{ padding: 30, borderBottomWidth: 1 }}>
          <Text>列表项 {i + 1}</Text>
        </View>
      ))}
    </Animated.ScrollView>
  );
}

内容的提问来源于stack exchange,提问作者Norman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 14:48:04