您希望聊天小工具在載入新訊息時自動聚焦於最後一則訊息。為此,您需要為每個訊息建立一個動態引用,並使用滾動函數滾動到最後一個元素。
以下是具體操作方法:
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中文網其他相關文章!