我想使用 react 钩子将屏幕滚动到底部,我在 Messages.js 组件中收到一个消息数组,并将每条消息发送到 Message.js 组件以根据用户加载,但我无法实现自动滚动到底部。 这是我的代码消息.js:
import React from 'react'
import Message from './Message';
function Messages(props) {
return (
<div>
{props.messageDetails.map((message) =>
<div key={message.Time_Stamp}>
{
<Message
messageBy={message.Sender}
messageTime={message.Time}
message={message.Message}
userName={props.userName}
/>
}
</div>)
}
</div>
)
}
export default Messages
您必须访问容器 DOM 元素并在每次数组更改时调用element.scroll()
函数messageDetails
import React, { useEffect, useRef } from 'react'
import Message from './Message';
function Messages({messageDetails, userName}) {
const containerRef = useRef(null);
useEffect(() => {
if(containerRef && containerRef.current) {
const element = containerRef.current;
element.scroll({
top: element.scrollHeight,
left: 0,
behavior: "smooth"
})
}
}, [containerRef, messageDetails])
return (
<div ref={containerRef}>
{messageDetails.map(({Time_Stamp, Sender, Time, Message}) =>
<div key={Time_Stamp}>
<Message
messageBy={Sender}
messageTime={Time}
message={Message}
userName={userName}
/>
</div>)}
</div>
)
}
export default Messages
import React, { useEffect } from 'react'
import Message from './Message';
function Messages({messageDetails, userName}) {
var y = window.scrollY;
useEffect(() => {
var element = document.querySelector('.ref');
window.scroll({
top: element.scrollHeight,
left: 0,
});
},[messageDetails])
return (
<div className="ref" >
{messageDetails.map((message) =>
<div key={message.Time_Stamp}>
{
<Message
messageBy={message.Sender}
messageTime={message.Time}
message={message.Message}
userName={userName}
/>
}
</div>)
}
</div>
)
}
export default Messages