ReactJS v18 讨论页面滚动到指定帖子:使用 URL 哈希和生命周期方法
要通过'/discussions/:id#posts-47'在页面加载完成后滚动到第47条posts的位置,可以使用React的生命周期方法和DOM操作完成。/n/n首先,你可以在讨论页面组件的'componentDidMount'生命周期方法中获取URL中的id和要滚动到的posts编号。可以使用'window.location'来获取URL中的哈希部分,并使用正则表达式提取相关信息。/n/n然后,在获取到要滚动到的posts编号后,你可以使用React的'ref'属性来标记每个posts元素,以便可以通过ref引用它们。在加载更多的按钮上也要添加一个ref。/n/n在加载更多的按钮上添加一个点击事件处理程序,当点击按钮时,使用'scrollIntoView()'方法来使下一组posts可见。你可以使用'setState()'来更新组件的状态,以便在加载更多时重新渲染posts。/n/n下面是一个示例代码:/n/njsx/nimport React, { Component } from 'react';/n/nclass DiscussionPage extends Component {/n constructor(props) {/n super(props);/n this.state = {/n id: '',/n scrollToPost: ''/n };/n }/n/n componentDidMount() {/n const { id } = this.props.match.params;/n const scrollToPost = window.location.hash.match(/#posts-(/d+)/);/n if (scrollToPost) {/n this.setState({ id, scrollToPost: scrollToPost[1] });/n }/n }/n/n handleLoadMore = () => {/n // 加载更多posts的逻辑/n }/n/n render() {/n const { id, scrollToPost } = this.state;/n const posts = []; // 根据id获取posts的逻辑/n/n return (/n <div>/n {posts.map((post, index) => (/n <div key={post.id} ref={scrollToPost === post.id ? 'scrollToPost' : null}>/n {/* 展示posts的内容 */}/n </div>/n ))}/n <button onClick={this.handleLoadMore}>加载更多</button>/n </div>/n );/n }/n}/n/nexport default DiscussionPage;/n/n/n在'render'方法中,我们使用了'ref'属性来标记要滚动到的posts元素,如果该元素是要滚动到的posts编号对应的元素,则设置ref为'scrollToPost'。在'componentDidMount'方法中,我们会获取URL中的要滚动到的posts编号,并将其存储在组件的状态中。/n/n在'handleLoadMore'方法中,你可以编写加载更多posts的逻辑。当点击加载更多按钮时,你可以使用'scrollIntoView()'方法来使下一组posts可见。你可以通过ref引用标记的'scrollToPost'来获取要滚动到的posts元素,并调用'scrollIntoView()'方法使其可见。/n/n请注意在加载更多posts时,你需要更新组件的状态,以便重新渲染posts。这样,新加载的posts元素将被标记为'scrollToPost',并在下次渲染时被滚动到。/n/n这是一个基本的示例,你可以根据你的具体需求进行修改和扩展。希望这可以帮助到你!
原文地址: https://www.cveoy.top/t/topic/qws1 著作权归作者所有。请勿转载和采集!