我正在React中实现聊天视图,所期望的行为是每当新数据被推入dataSource,聊天视图(无限列表)滚动到底部,有许多实现,有些在这里找到:How to scroll to bottom in react?。然而,当我尝试实现它时,我会出现这种奇怪的行为,即窗口中的所有视图都被300 if“向上推送”,好像是要容纳位于列表视图底部的这个新的<div>。我的执行情况如下:
import React, {useEffect, useRef} from "react";
import { createStyles, makeStyles, Theme } from "@material-ui/core/styles";
import InfiniteScroll from 'react-infinite-scroll-component';
const row_1 = 2.5;
const row_chat = 4
const useStyles = makeStyles((theme: Theme) => createStyles({
container: {
width: '40vw',
height: `calc(100vh - 240px)`,
position: 'relative',
padding: theme.spacing(3),
},
}));
const chat_container_style = {
width: '40vw',
height: `calc(100vh - 240px - ${row_chat}vh - ${row_1}vh)`,
}
function ChatView(props) {
const classes = useStyles();
const { _dataSource } = props;
// scroll to bottom
const messagesEndRef = useRef(null)
const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" })
}
useEffect(() => {
scrollToBottom()
}, [_dataSource]);
return (
<div className={classes.container}>
{/* chat window */}
<InfiniteScroll
dataLength={_dataSource.length}
next={() => { return }}
hasMore={true}
loader={<></>}
style={chat_container_style}
>
{_dataSource.map((item, index) => {
return (
<div {...props} key={index} item={item}>
{`item: ${index}`}
</div>
)
})}
{/* putting an item here push all divs upward */}
<div ref={messagesEndRef} />
</InfiniteScroll>
</div>
)
}注意,使用<InfiniteScroll/>并不是行为的原因,实际上,如果我将ref={messagesEndRef}放入任何视图中,它会将所有视图推上视口。
发布于 2022-01-03 15:18:31
这个问题已经解决了。问题的根源是scrollIntoView函数,它正在滚动整个页面,而不仅仅是listView,下面是具有正确参数的正确scrollIntoView函数:
const scrollDivRef = createRef();
useEffect(() => {
scrollDivRef.current?.scrollIntoView({
block : 'nearest',
inline : 'start',
behavior: 'smooth',
})
}, [_dataSource.length]);下面是ref如何嵌套在DOM中:
<InfiniteScroll
next={() => { return }}
hasMore={true}
loader={<></>}
style={chat_container_style}
dataLength={_dataSource.length}
>
{_dataSource.map((item, index) => (
<BubbleView {...props} key={index} item={item}/>
))}
<div style={refDivStyle} ref={scrollDivRef}/>
</InfiniteScroll>这个问题与我如何布局样式表无关。
https://stackoverflow.com/questions/70560471
复制相似问题