[英]How to scroll to the desired element in React?
I have a question - I have a list that is in a separate popup with a limited height.我有一个问题 - 我有一个列表,它位于一个高度有限的单独弹出窗口中。 After this height, a side scroll appears.在这个高度之后,会出现一个侧卷轴。 I need to scroll to a specific element automatically when that component is rendered.渲染该组件时,我需要自动滚动到特定元素。 How to implement it?如何实施? I just can't figure out how to scroll to a certain element.我只是不知道如何滚动到某个元素。
Below is an example of my jsx code下面是我的 jsx 代码示例
<ul className={style.list}>
{itemsForRender?.length ? (
itemsForRender.map((item) => (
<li className={style.item} key={item.id}>
<button
type="button"
className={
activeItem === item.id
? `${style.button} ${style.activeClass}`
: style.button
}
onClick={() => selectItem(item.id)}
>
{item.name}
</button>
</li>
))
) : (
<p className={style.searchSubtitle}>
Just text
</p>
)}
</ul>
Use this code :使用此代码:
const ScrollDemo = () => { const myRef = useRef(null) const executeScroll = () => myRef.current.scrollIntoView() // run this function from an event handler or an effect to execute scroll return ( <> <div ref={myRef}>Element to scroll to</div> <button onClick={executeScroll}> Click to scroll </button> </> ) }
I had used Element.scrollIntoView() Method in React with making a reference of element i want to scroll to, here is the example:我在 React 中使用了 Element.scrollIntoView() 方法来引用我想要滚动到的元素,这里是示例:
function TestComponent() {
const testRef = useRef(null);
const scrollToElement = () => testRef.current.scrollIntoView();
// Once the scrollToElement function is run, the scroll will show the element
return (
<>
<div ref={testRef}>Element you want to view</div>
<button onClick={scrollToElement}>Trigger the scroll</button>
</>
);
}
you can use scrollIntoView() where you want scroll automatically你可以在你想自动滚动的地方使用scrollIntoView()
document.getElementById(element-id).scrollIntoView({behavior: 'smooth'})
you can use this in a useEffect() to run it when component is rendered您可以在useEffect()中使用它来在渲染组件时运行它
I hope this would be helpful.我希望这会有所帮助。 thanks谢谢
const scrollRef = useRef([]);
useEffect(() => {
// here you call the function scrollToSection and pass the id where you want to scroll
}, [])
const scrollToSection = id => {
if (scrollRef.current.length) {
scrollRef.current[id].scrollIntoView();
}
};
<ul className={style.list}>
{itemsForRender?.length ? (
itemsForRender.map((item) => (
<li className={style.item} ref={ref => (scrollRef.current[item.id] = ref)} key={item.id}>
<button
type="button"
className={
activeItem === item.id
? `${style.button} ${style.activeClass}`
: style.button
}
onClick={() => selectItem(item.id)}
>
{item.name}
</button>
</li>
))
) : (
<p className={style.searchSubtitle}>
Just text
</p>
)}
</ul>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.