Jam*_*man 6 javascript scroll reactjs ionic-framework ionic4
我正在尝试使用 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>
);
};
Run Code Online (Sandbox Code Playgroud)
该scrollToTop函数应该滚动到 id 为 'page' 的元素的顶部,但不是。单击按钮时我没有收到任何错误,而是什么也没有发生。
我知道这是在 Angular 中实现的微不足道的事情,但我在使用 React 时遇到了麻烦。任何帮助都会非常感谢。
您可以使用IonContentscrollToTop方法执行此操作,但您必须先启用scrollEvents。在离子反应中,可以使用 访问这些方法refs。看起来反应不大,但至少目前有效。
........
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>
.....
);
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1425 次 |
| 最近记录: |