gpt4 book ai didi

javascript - 使用 Ionic React 添加滚动按钮

转载 作者:行者123 更新时间:2023-11-29 22:45:44 26 4
gpt4 key购买 nike

我正在尝试使用 Ionic React 添加一个滚动到页面顶部的按钮。到目前为止,这是我的代码的一部分 -

...
function scrollToTop() {
return document.getElementById("page")!.scrollTop;
}

const Home: React.FC = () => {
return (
<IonPage>
<IonHeader>
<IonToolbar>
<IonButtons slot="start">
<IonMenuButton />
</IonButtons>
<IonTitle slot="end">Ionic Template - JB</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent id={"page"}>
<IonCard className="welcomeImage">
<img src="/assets/welcomeBacking.jpg" alt=""/>
<IonCardHeader>
<IonCardTitle>Welcome!</IonCardTitle>
<IonCardSubtitle>To this Ionic Template</IonCardSubtitle>
</IonCardHeader>
<IonCardContent>
Lorem ipsum........
</IonCardContent>
</IonCard>
{/*Checklist*/}
<IonList>
{form.map(({val, isChecked, isDisabled}) => (
<IonItem key={val}>
<IonLabel>{val}</IonLabel>
<IonCheckbox slot={"start"} value={val} checked={isChecked} disabled={isDisabled} />
</IonItem>
))}
</IonList>
<IonButton onClick={scrollToTop}>Scroll to top</IonButton>
</IonContent>
</IonPage>
);
};

scrollToTop 函数应该滚动到 ID 为“page”的元素的顶部,但事实并非如此。单击按钮时我没有收到任何错误,而是什么也没有发生。

我知道这在 Angular 中实现起来很简单,但我在使用 React 时遇到了问题。任何帮助都会非常感谢。

最佳答案

您可以使用 IonContentscrollToTop 方法来做到这一点,但您必须先启用 scrollEvents。在 ionic react 中,可以使用 refs 访问这些方法。看起来 react 不大,但至少目前有效。

........    
import React, {useRef} from 'react';

const Home: React.FC = (props) => {
const contentRef = useRef<HTMLIonContentElement | null>(null);
const scrollToTop= () => {
contentRef.current && contentRef.current.scrollToTop();
};
return (
.....
<IonContent ref={contentRef} scrollEvents={true}>
................
<IonButton onClick={()=>scrollToTop()}>Scroll to top</IonButton>
</IonContent>
.....
);
};

关于javascript - 使用 Ionic React 添加滚动按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58730178/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com