[英]React How do I make the page allows scrolled down?
我正在嘗試創建聊天消息,但我不知道如何讓聊天每次都向下滾動。 當用戶輸入新消息時,我希望它始終向下滾動,以便我們可以在底部看到新消息。 我覺得這是需要編輯的。
const MessageContainer = styled.div`
display: flex;
flex-direction: column;
overflow-y: auto;
`
您可以在聊天底部保留一個虛擬 div,然后在組件更新時滾動到它(即 state 在添加新消息時更新):
const [message, setMessage] = useState([]);
const [text, setText] = useState(1);
const messagesEndRef = useRef(null);
const scrollToBottom = () => {
messagesEndRef.current.scrollIntoView({ behavior: "smooth" });
};
useEffect(scrollToBottom, [message]);
const addText = () => {
setMessage([...message, text]);
setText((data) => data + 1);
}
return (
<div className="App">
<div className="data">
{message.map(m => (
<span key={m}>{m}</span>
))}
<div ref={messagesEndRef} />
</div>
<button onClick={addText} className={'button'}>Add Text</button>
</div>
);
https://codesandbox.io/s/great-feynman-5m3i7?file=/src/App.js
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.