首页 > 解决方案 > SwipeableViews 如何将 updateHeight() 作为道具传递

问题描述

所以我使用 SwipeableViews 没有在页面之间滑动。我的问题是每个页面都有不同的动态长度。我将 animateHeight 设置为 true,但它仅在选项卡更改时为高度设置动画。在文档中它说函数 updateHeight() 可以解决这个问题。 https://react-swipeable-views.com/api/api/

由于我缺乏知识,我无法获得 updateHeight,因为我在基于类的应用程序上看到了所有示例。我在基于功能的应用程序中构建了我的应用程序。我只是想不通将它作为道具传递给以后调用它。

标签: javascriptreactjs

解决方案


我找到了一种使用 updateHeight 函数的方法。这有点hacky,但它有效。我添加了一个间隔和超时来补偿数据加载/慢速机器。useEffect 清除页面卸载时的间隔。

可能有更好的解决方案,但这是我迄今为止发现的!

export function SwipeView() {
 const [ref, setRef] = useState(null);

 const onRefChange = useCallback((node: SwipeableViews & HTMLDivElement) => {
   // hacky solution to update the height after the first render. Height is not set correctly on initial render
 setRef(node); // e.g. change ref state to trigger re-render
   if (node === null) {
     return;
   } else {
     interval = setInterval(() => {
       // @ts-ignore typings are not correct in this package
       node.updateHeight();
     }, 100);
     setTimeout(() => {
       clearInterval(interval);
     }, 10000);
   }
 }, []);

 useEffect(() => {
   return () => clearInterval(interval);
 }, [interval]);

 return (
   <SwipeableViews
     animateHeight
     ref={onRefChange}
   >
     {children}          
   </SwipeableViews>
 );
}

推荐阅读