自动转到在 React Virtual Dom 中创建的 div 元素



我的网页使用 React 组件。在其组件之一的渲染函数中,div 元素如下所示:

<div id='myid'>
{/* ... */}
</div>

正在使用。重新加载页面后,我们需要转到其中一个div。例如,重新加载该页面后,我们可能需要自动转到 id 等于myid<div>元素。请注意,<div>在 React 虚拟 DOM 中,因此像document.getElementById这样的函数可能无法正常工作(就像我发生的那样(。这可能吗?

挂载组件时,<div>id将最终出现在文档中,因此您可以在componentDidMount钩中滚动到那里。

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>
);
}
}

您仍然可以使用 findDOMNode 获取元素

const div = ReactDOM.findDOMNode(this.refs.mydiv);

然后在渲染函数中

<div ref="mydiv"></div>

终于

window.scrollTo(0, div.offsetTop);

如果元素是由 react 渲染的,你应该使用ref来获取元素在其上调用scrollIntoView()

class MyComponent extends Component {
ref = elem => elem.scrollIntoView();
render() {
return (
<div ref={this.ref}>{/* ... */}</div>
);
}
}

使用getElementById()React.findDOMNode也可能有效,但是您需要知道组件是否已挂载。如果在组件内部进行滚动(推荐(,则使用ref是最佳解决方案。

最新更新