簡體   English   中英

React 如何使頁面允許向下滾動?

[英]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

你可以試試:

const MessageContainer = styled.div`
    display: flex;
    flex-direction: column-reverse;
    overflow-y: auto;
`

或者

我為您制作了示例(CodeSandBox),但我不確定這是否是您想要的。

編輯文本字段選擇開始

它喜歡:

在此處輸入圖像描述

希望能幫到你!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM