[英]How to scroll to a particular active item in react when only that particular list is having overflow property but the parent overflow is hidden?
[英]Scroll to particular Item using ID of that item in react?
我試圖滾動到特定的行項目以使用該項目的 ID 做出反應。 我有特定行的 ID,但無法移動到那里。
goToViolation=(id)=>{
const violation = id ;
window.scrollTo({
top:violation.current.offsetTop,
behavior:"smooth"});
};
if (isDrillDown) {
isRowSelected = index === rowIndex % 20;
if(isRowSelected){
this.goToViolation(row.id);
}
}
為了滾動到一個元素,您需要該元素的 ref。
<div onClick={this. goToViolation("row-id")} id="row-id"></div>
然后在你的函數中
goToViolation=(id)=>{
const violation = document.getElementById(id);
window.scrollTo({
top:violation.current.offsetTop,
behavior:"smooth"
`});
};
但是這種方法沒有被引用,而是使用 refs 來充分利用 react 的好處。
我同意@MuhammadAsad 的觀點,即直接操作 DOM 不是 React 的方式。
相反,您可以使用useRef
鈎子並將 ref 傳遞給您的 JSX 元素。
之后,您可以從.current
屬性中收集 DOM 引用。
然后你可以做
**your ref**.current.scrollIntoView({ behavior: "smooth", block: "start" });
例子,
你的變量聲明。
const violationRef = useRef(null);
您要滾動到的 JSX 元素。
<div ref={violationRef} ></div>
您的按鈕將綁定 onClick 事件。
<button onClick={goToViolation} />
你的處理函數
const goToViolation=(id)=>{
violationRef.current.scrollIntoView({ behavior: "smooth", block: "end" });
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.