[英]How to scroll at bottom in react on button
当用户单击按钮时,我试图在底部向下滚动用户。 我真的很努力,但没有找到任何解决方案。 有人可以帮助我如何实现我的目标。
谢谢
您可以使用document.body.offsetHeight
获取页面的高度并使用windows.scroll
滚动到它。 如果您需要支持 IE11 及更低版本,请使用window.scroll(0, document.body.offsetHeight);
import React from 'react';
function App() {
function handleScroll() {
window.scroll({
top: document.body.offsetHeight,
left: 0,
behavior: 'smooth',
});
}
return <button type="button" onClick={handleScroll}>Scroll</button>;
}
您安装 react-scroll-button npm package
npm i react-scroll-button
使用代码
import React, {Component} from 'react'
import ScrollButton from 'react-scroll-button'
class ScrollComponent extends Component {
render() {
return (
<ScrollButton
behavior={'smooth'}
buttonBackgroundColor={'red'}
iconType={'arrow-up'}
style= {{fontSize: '24px'}}
/>
);
}
}
有几种方法可以实现这一点:
const onClick = () => {
window.scroll({
bottom: document.body.scrollHeight, // or document.scrollingElement || document.body
left: 0,
behavior: 'smooth'
});
}
...
return <button onClick={onClick} ... />
和另一种方式ref
。 您需要在页面底部添加一个元素并在单击按钮后滚动到它:
const bottomRef = React.useRef();
const onClick = () => {
bottomRef.current.scrollIntoView();
}
...
return (
<div className="container">
<button onClick={onClick} />
<div className="bottomContainerElement" ref={bottomRef} />
<div>
)
您可以使用useRef
挂钩来滚动到特定的 div。 这是反应和使用反应钩子最推荐的方法。
import React, { useRef } from "react";
import "./styles.css";
export default function App() {
const divRef = useRef();
return (
<div className="App">
<button
onClick={() => {
divRef.current.scrollIntoView({ behavior: "smooth" });
}}
>
Scroll to Bottom
</button>
<div className="bigDiv" />
<div className="bigDiv" />
<div className="bigDiv" />
<div className="bigDiv" ref={divRef}>
Scrolled Here
</div>
</div>
);
}
.App {
font-family: sans-serif;
text-align: center;
}
.bigDiv {
height: 100vh;
width: 100%;
background: cyan;
border: 1px solid violet;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.