简体   繁体   English

在反应中使用该项目的 ID 滚动到特定项目?

[英]Scroll to particular Item using ID of that item in react?

I was Trying to scroll to particular row item in react using ID of that item.我试图滚动到特定的行项目以使用该项目的 ID 做出反应。 I have the ID of particular row but not able to move there.我有特定行的 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. i was getting the ID from this Condition and i am passing it to the above function and using scrollTo function.我正在从这个 Condition 获取 ID,我将它传递给上面的函数并使用 scrollTo 函数。

In order to scroll to an element you need ref for that element.为了滚动到一个元素,您需要该元素的 ref。

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

Then in your function然后在你的函数中

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

But this approach is not referred, instead use refs to fully levarage the benefits of react.但是这种方法没有被引用,而是使用 refs 来充分利用 react 的好处。

I agree with @MuhammadAsad that manipulating the DOM directly is not a React way.我同意@MuhammadAsad 的观点,即直接操作 DOM 不是 React 的方式。

Instead you can use useRef hook and pass the ref to your JSX element.相反,您可以使用useRef钩子并将 ref 传递给您的 JSX 元素。

After that, you can collect the DOM reference from .current property.之后,您可以从.current属性中收集 DOM 引用。

Then you can just do然后你可以做

**your ref**.current.scrollIntoView({ behavior: "smooth", block: "start" });

Example,例子,

Your variable declaration.你的变量声明。

const violationRef = useRef(null);

Your JSX element which you want to scroll to.您要滚动到的 JSX 元素。

<div ref={violationRef} ></div>

Your button which will bind onClick event.您的按钮将绑定 onClick 事件。

<button onClick={goToViolation} />

Your handler function你的处理函数

const goToViolation=(id)=>{
  violationRef.current.scrollIntoView({ behavior: "smooth", block: "end" });
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM