我的网页使用 React 组件。在其组件 div 元素之一的呈现函数中,如下所示:
<div id='myid'>
{/* ... */}
</div>
正在使用中。重新加载页面后,我们需要转到其中一个 div。例如,在重新加载该页面后,我们可能需要自动转到 <div>
。 id 等于 myid
的元素.请注意 <div>
在 React 虚拟 DOM 中,所以功能类似于 document.getElementById
可能不起作用(因为它正在发生在我身上)。这可能吗?
最佳答案
<div>
和 id
将在安装组件时出现在文档中,因此您可以在 componentDidMount
中滚动到那里钩子(Hook)。
示例
class App extends React.Component {
componentDidMount() {
document.getElementById("myid").scrollIntoView();
}
render() {
return (
<div>
<div style={{ height: 1000 }}>Hello CodeSandbox</div>
<div style={{ height: 1000 }} id="myid">
Scroll here
</div>
</div>
);
}
}
关于javascript - 自动转到在 React Virtual Dom 中创建的 div 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51115894/