Javascript 使用componentDidUpdate自动滚动到react中的锚定标记元素 我的网址

Javascript 使用componentDidUpdate自动滚动到react中的锚定标记元素 我的网址,javascript,reactjs,url,autoscroll,Javascript,Reactjs,Url,Autoscroll,HTML 这是可行的,但我正在寻找一个更好的方法来实现同样的目标 换句话说,我不想使用setTimeOut 我添加了setTimeOut,因为我发现document.getElementById(id)的值为null(第一次),我假设componentDidUpdate在整个渲染之前运行。我还使用了危险的LySetinerHTML。您认为document.getElementById(id)返回null是正确的,因为元素尚未呈现 使用React时,不要使用document.getElement

  • HTML
这是可行的,但我正在寻找一个更好的方法来实现同样的目标

换句话说,我不想使用setTimeOut


我添加了setTimeOut,因为我发现document.getElementById(id)的值为null(第一次),我假设componentDidUpdate在整个渲染之前运行。我还使用了危险的LySetinerHTML。

您认为
document.getElementById(id)
返回
null
是正确的,因为元素尚未呈现

使用React时,不要使用
document.getElementById()
。 React节点本身不是真正的DOM节点(例如,文本或元素节点),而是潜在DOM节点的表示

相反,使用钩子
useRef()

创建以下组件

import React, { useRef, useEffect }  from 'react';

export default observer( (props) => {
  const myRef = useRef();

  function scrollToComponent() {
    if (window.location.hash === '#api-doc') {
      myRef.current.scrollIntoView();
      myRef.current.focus();
    }
  }

  useEffect( () => scrollToComponent(), [] )

  return (
    <div ref={myRef} id="api-doc">
       ...
    </div>
  )
})
import React,{useRef,useffect}来自“React”;
导出默认观察者((道具)=>{
const myRef=useRef();
函数scrollToComponent(){
if(window.location.hash=='#api doc'){
myRef.current.scrollIntoView();
myRef.current.focus();
}
}
useEffect(()=>scrollToComponent(),[]))
返回(
...
)
})
使用
useffect
这种方式将(仅)在安装组件时触发。(因此避免了组件安装前JS运行的问题)

我命名的函数
scrollToComponent
将检查URL是否有散列,如果它通过了条件,它将滚动到ref

请记住将组件导入主文件

*注意:使用React路由器的链接可能是更好的解决方案。(但有一个我不熟悉)


    componentDidUpdate(){
        let id = this.props.history.location.hash.replace("#", "");
        let element = document.getElementById(id);
        setTimeout(() => {
            if (element) {
                element.scrollIntoViewIfNeeded(true);
            }
        }, 200);
    }
import React, { useRef, useEffect }  from 'react';

export default observer( (props) => {
  const myRef = useRef();

  function scrollToComponent() {
    if (window.location.hash === '#api-doc') {
      myRef.current.scrollIntoView();
      myRef.current.focus();
    }
  }

  useEffect( () => scrollToComponent(), [] )

  return (
    <div ref={myRef} id="api-doc">
       ...
    </div>
  )
})