【问题标题】:how can i resolve error ? : node.scrollTo is not a function我该如何解决错误? : node.scrollTo 不是函数
【发布时间】:2021-03-16 18:16:56
【问题描述】:

当我在 TodoItem 组件中运行 onPress 时,我希望执行 scrollTo 并向下滚动 y: height value

但如果我运行 onPress

node.scrollTo 不是函数

这是我的代码

(TodoList.js)

    import React, {useContext, useState, useEffect, createRef} from 'react';
    import {FlatList} from 'react-native';
    import {
      Dimensions,
      NativeSyntheticEvent,
      NativeScrollEvent,
      ScrollView,
    } from 'react-native';

    const TodoList = ({replycomment}) => {


      const height = Dimensions.get('window').height;
      const [tabIndex, setTabIndex] = useState(0);
      const flatListRef = React.useRef()
      const refScrollView = createRef();
    
      return (
        
        <FlatList
        ref={refScrollView}
          style={{height}}
          contentOffset={{x: 0, y: height}}
          renderItem={({item}) => (
            <TodoItem
            onPress={() => {
              const node = refScrollView.current;
              if (node) {
                node.scrollTo({x:0, y: height, animated: true});
              }
            }}
            />
          )}
        />

(TodoItem.js)

        import React, { useCallback, useState } from 'react';
        import {FlatList} from 'react-native';


        const TodoItem = ({onPress}) => {


        return (
            
        
        <MainContainer onPress={onPress}>
            <Label>hi</Label>
        </MainContainer>

我不确定为什么会发生此错误。我该如何修复我的代码?我想使用平面列表

【问题讨论】:

  • node 中存在的对象显然没有scrollTo 方法。

标签: javascript node.js reactjs react-native


【解决方案1】:

FlatListGithub 源代码中,我只能看到 4 种方法可以帮助实现 scroll 功能:-

scrollToEnd(params?: ?{animated?: ?boolean, ...})
scrollToIndex(params: {
    animated?: ?boolean,
    index: number,
    viewOffset?: number,
    viewPosition?: number,
    ...
  })
scrollToItem(params: {
    animated?: ?boolean,
    item: ItemT,
    viewPosition?: number,
    ...
  })
scrollToOffset(params: {animated?: ?boolean, offset: number, ...}) 

我认为您需要使用上述任何一个(因为FlatList 没有实现它自己的scrollTo)。我可以看到VirtualizedList 内部的scrollTo 用法,它是由FlatList 内部返回的。

链接到源代码 - https://github.com/facebook/react-native/blob/master/Libraries/Lists/FlatList.js

【讨论】:

    【解决方案2】:

    你可以尝试使用这样的东西吗:

    node.scrollIntoView({ behavior: 'smooth', block: 'start' })

    【讨论】:

      猜你喜欢
      • 2023-02-22
      • 2020-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-24
      • 2016-11-18
      相关资源
      最近更新 更多