问题
- My URL
https://abc1234.com/users#api-doc
- HTML
<div className={parent}>
<div className={child}>
{someContent}
<a id="api-doc">Hello API</a>
</div>
</div>
I am writing the page in ReactJS. I need to implement a way so that the page should auto-scroll down to the Hash i.e. api-doc but somehow it's not auto-scrolling on page load (very first time).
I tried a workaround which is like this
componentDidUpdate(){
let id = this.props.history.location.hash.replace("#", "");
let element = document.getElementById(id);
setTimeout(() => {
if (element) {
element.scrollIntoViewIfNeeded(true);
}
}, 200);
}
It's working but I am looking for a better way to achieve the same
In other words, I do not want to use setTimeOut.
I added setTimeOut cause I found that document.getElementById(id) is giving null (very first time), I am assuming that somehow componentDidUpdate is running before the entire render. I have also used dangerouslySetInnerHTML .
来源:https://stackoverflow.com/questions/64224547/auto-scroll-to-anchor-tag-element-in-react-using-componentdidupdate