dev*_*ent 5 javascript scroll cross-browser reactjs
我正在使用 Redux 在 React 中构建一个跨浏览器的聊天小部件。聊天小部件中的事件是分页的,通过滚动到事件列表的顶部来触发获取较旧的事件。事件被添加到事件列表中。容器的滚动位置在重新渲染时保持在顶部,这会触发更多的重新获取。冲洗并重复。
我尝试在获取之前存储滚动位置,并在获取成功后将新高度与旧高度进行比较,但没有成功。
fetchOldMessages = () => {
//getMoreMessages updates the redux store, where messages are connected from.
const { getMoreMessages, messages } = this.props
const { isFetching, fetchedEventIds } = this.state
const oldestMessage = messages[0]
if (!oldestMessage || isFetching || fetchedEventIds.includes(oldestMessage.id) || !this.scrollContainerIsReady())
return
const currentPosition = this.ContainerRef.current.scrollHeight
this.setState({ isFetching: true}, () => {
getMoreMessages(oldestMessage).then(() => {
const newPosition = this.ContainerRef.current.scrollHeight - currentPosition
this.scrollContainerRefTo({left: 0, top: currentLocation})
})
this.setState({
isFetching: false,
fetchedEventIds: [...this.state.fetchedEventIds, oldestMessage.id],
})
})
})
Run Code Online (Sandbox Code Playgroud)
scrollContainerRefTo = opts => {
if (!this.scrollContainerIsReady()) return null
if (this.ContainerRef.current.scrollTo) {
return this.ContainerRef.current.scrollTo(opts)
}
this.ContainerRef.current.scrollLeft = opts.left
this.ContainerRef.current.scrollTop = opts.top
}
Run Code Online (Sandbox Code Playgroud)
render() {
const { messages } = this.props
return (
<div ref={this.ContainerRef}>
{messages.reduce((acc, message, index) => {
acc.push(
<Event key={message.id} message={message} onVisibile={index === 0 ? fetchOldMessages: null} />
)
return acc
},[])}
</div>
)
}
Run Code Online (Sandbox Code Playgroud)
从用户的角度来看,我希望容器在消息被添加时不会滚动。它应该留在原处。
谢谢!
| 归档时间: |
|
| 查看次数: |
312 次 |
| 最近记录: |