React 如何使页面允许向下滚动? [英] React How do I make the page allows scrolled down?

查看:69
本文介绍了React 如何使页面允许向下滚动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

const MessageContainer = styled.div`显示:弹性;弹性方向:列;溢出-y:自动;`

解决方案

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

const [message, setMessage] = useState([]);const [text, setText] = useState(1);const messagesEndRef = useRef(null);const scrollToBottom = () =>{messagesEndRef.current.scrollIntoView({行为:平滑"});};useEffect(scrollToBottom, [消息]);const addText = () =>{setMessage([...message, text]);setText((data) => data + 1);}返回 (

<div className="数据">{message.map(m => (<span key={m}>{m}</span>))}<div ref={messagesEndRef}/>

<button onClick={addText} className={'button'}>添加文本</button>

);

https://codesandbox.io/s/great-feynman-5m3i7?file=/src/App.js

I'm trying to create a chat message and I have no idea how to make the chat be scrolled down every time. When the user inputs new messages, I want it to be always scrolled down so that we can see the new message at the bottom. I feel like this is what needs to be edited.

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

解决方案

You can keep a dummy div at the bottom of your chat and then scroll to it whenever your component is updated (i.e. state updated as new messages are added):

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

这篇关于React 如何使页面允许向下滚动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆