如何滚动容器自动滚动和React?

rsl1atfo  于 2023-08-07  发布在  React
关注(0)|答案(1)|浏览(121)

我用react写了这段代码

useEffect(()=>{
      if(!currentTitle && value && message){
        setCurrentTitle(value)
      }
      if(currentTitle && value && message){   
          setPreviousChats(prevChats =>{  
            return [...prevChats, {
              title: currentTitle,
              role: "auth",
              content: value
            },
            {
              title: currentTitle,
              role: "message:",
              content: message.content
              
            }
          ]
          
          })
        
      }
    }, [message, currentTitle])`

código html`return (
    <div>
        <ul className="containerMessage">
            {currentChat?.map((chatMessage, index)=> <li key={index}>
              <p className='role'>{chatMessage.role}</p>
              <p>{chatMessage.content}</p>
            </li>)}
        </ul>
</div>
<div>
<input value={value == null ? ' ' : value} onChange={(e)=> setValue(e.target.value)}/>
            <div id="submit" onClick={getMessages}>send</div>`
</div>

字符串
输入采取的消息由用户输入,并创建了一个在DOM与响应消息,但是,要检查最后的消息,有必要手动滚动容器滚动,我想滚动自动滚动作为新的消息返回

umuewwlo

umuewwlo1#

我强烈建议你尝试这样的东西,对我有好处,让它适应你的代码:

import { useEffect, useRef } from 'react';

// ... other parts of your component

const messagesEndRef = useRef(null)

const scrollToBottom = () => {
  messagesEndRef.current?.scrollIntoView({ behavior: "smooth" })
}

useEffect(() => {
  scrollToBottom()
}, [currentChat]); // or replace currentChat with the state that changes when a new chat message is added or first loaded.

return (
    <div>
        <ul className="containerMessage">
            {currentChat?.map((chatMessage, index) => 
              <li key={index}>
                <p className='role'>{chatMessage.role}</p>
                <p>{chatMessage.content}</p>
              </li>
            )}
            <div ref={messagesEndRef} /> {/* This is the element we're going to scroll to */}
        </ul>
    </div>
    <div>
      <input value={value == null ? ' ' : value} onChange={(e)=> setValue(e.target.value)}/>
      <div id="submit" onClick={getMessages}>send</div>
    </div>
);

字符串
请注意,我添加了新的空div、ref和useEffect以及一个滚动到按钮的函数。

相关问题