react-window用InfiniteLoader包裹后如何获取ref?

import { VariableSizeList as List, areEqual } from 'react-window';
import InfiniteLoader from 'react-window-infinite-loader';

const Demo = ()=>{
    const ref = useRef();

    const click = ()=>{
        // 这里报错,ref没有scrollToItem方法
        ref.scrollToItem(0)
    }

return <div>
<Button onClick={click}>click</Button>
<ListWrap ref={ref}></ListWrap>
</div>
}
const ListWrap = ({ hasNextPage, isNextPageLoading, loadNextPage }) => {
 
  return (
    <InfiniteLoader isItemLoaded={isItemLoaded} itemCount={itemCount} loadMoreItems={loadMoreItems}>
      {({ onItemsRendered, ref }) => {
        return (
          <List
            ref={ref}
          >
            {Cell}
          </List>
        );
      }}
    </InfiniteLoader>
  );
};

类似上面的代码, 如何获取List的实例ref呢?

阅读 2.6k
1 个回答
import { useRef } from 'react';
import { VariableSizeList as List, areEqual } from 'react-window';
import InfiniteLoader from 'react-window-infinite-loader';

const Demo = () => {
  const listRef = useRef();

  const click = () => {
    if (listRef.current) {
      listRef.current.scrollToItem(0);
    }
  };

  return (
    <div>
      <Button onClick={click}>click</Button>
      <ListWrap listRef={listRef} />
    </div>
  );
};

const ListWrap = ({ hasNextPage, isNextPageLoading, loadNextPage, listRef }) => {
  return (
    <InfiniteLoader isItemLoaded={isItemLoaded} itemCount={itemCount} loadMoreItems={loadMoreItems}>
      {({ onItemsRendered, ref }) => {
        return (
          <List
            ref={(instance) => {
              ref(instance);
              listRef.current = instance;
            }}
          >
            {Cell}
          </List>
        );
      }}
    </InfiniteLoader>
  );
};
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Microsoft
子站问答
访问
宣传栏