您希望聊天小部件在加载新消息时自动聚焦于最后一条消息。为此,您需要为每条消息创建一个动态引用,并使用滚动函数滚动到最后一个元素。
以下是具体操作方法:
const ScrollDemo = () => { const myRef = useRef(null); const executeScroll = () => myRef.current.scrollIntoView(); // run this function from an event handler or an effect to execute scroll return ( <> <div ref={myRef}>Element to scroll to</div> <button onClick={executeScroll}>Click to scroll</button> </> ); };
class ReadyToScroll extends Component { constructor(props) { super(props); this.myRef = React.createRef(); } render() { return <div ref={this.myRef}>Element to scroll to</div>; } executeScroll = () => this.myRef.current.scrollIntoView(); // run this method to execute scrolling. }
class ReadyToScroll extends Component { render() { return ( <div ref={(ref) => (this.myRef = ref)}>Element to scroll to</div> ); } executeScroll = () => this.myRef.scrollIntoView(); // run this method to execute scrolling. }
以上是如何在 React 中滚动到某个元素?的详细内容。更多信息请关注PHP中文网其他相关文章!