在react中使用该项目的ID滚动到特定项目



我试图使用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);
}
}
  1. 我从这个Condition中获取ID,并将其传递给上面的函数,并使用scrollTo函数

为了滚动到一个元素,您需要该元素的ref。

<div onClick={this.goToViolation("row-id")} id="row-id"></div>

然后在你的功能

goToViolation=(id)=>{
const violation = document.getElementById(id); 
window.scrollTo({
top:violation.offsetTop,
behavior:"smooth"
});
};

我同意@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" });
};

最新更新