【问题标题】:React How do I make the page allows scrolled down?React 如何使页面允许向下滚动?
【发布时间】:2021-05-28 14:51:35
【问题描述】:

我正在尝试创建聊天消息,但我不知道如何让聊天每次都向下滚动。当用户输入新消息时,我希望它始终向下滚动,以便我们可以在底部看到新消息。我觉得这是需要编辑的。

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

【问题讨论】:

  • 用例是:当用户按下发送按钮时,窗口添加滚动到底部,或者在聊天室中添加新消息时?
  • 当新消息添加到聊天室时,我希望它保持在底部,这样您就不必一直向下滚动才能看到新消息

标签: javascript reactjs styled-components


【解决方案1】:

您可以在聊天底部保留一个虚拟 div,然后在您的组件更新时滚动到它(即状态随着新消息的添加而更新):

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

【讨论】:

  • 哇,这个也很有魅力!非常感谢:)
  • @YongPark 如果这个答案对你有用,请点赞,谢谢:)
【解决方案2】:

你可以试试:

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

或者

我为你制作了 sample(CodeSandBox),但我不确定这是否是你想要的。

它喜欢:

希望能帮到你!

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2015-01-19
  • 1970-01-01
  • 2012-05-09
  • 1970-01-01
  • 2019-03-28
  • 2012-02-05
  • 2012-08-27
  • 1970-01-01
相关资源
最近更新 更多