componentDidUpdate滚动至底部时,项目加载
我有一个名单,我想滚动至底部,我有我的部分编码这样componentDidUpdate滚动至底部时,项目加载
class Msg extends Component {
componentDidUpdate() {
if(this.container){
this.container.scrollTop = this.container.scrollHeight
}
}
render() {
return(
<div ref={elem = this.container = elem}>
<Item />
<Item />
<Item />
</div>
)
}
}
它的工作。但问题是每当组件重新提交时它都会滚动。 Msg有很多子组件,触发子组件的状态会导致Msg组件再次呈现,如何解决这个问题?
解释它像一个正常的用户:
用户向上滚动列表,然后单击下拉某处时,componentDidUpdate触发,造成滚动底部。
要在组件呈现时第一次滚动到底部,应使用componentDidMount
生命周期挂钩。
如果您希望列表在每次添加元素时滚动,您可以使用现在使用的componentDidUpdate
钩子,但不是每次都操作滚动顶部,请检查您正在渲染的项目数是否已更改。现在,您每次更新组件时都要设置滚动条顶部。
componentDidUpdate
得到双方先前的道具和以前的状态参数,所以你可以写这样的事情:
componentDidUpdate(prevProps, prevState) {
if (this.props.items.length > prevProps.items.length) {
this.refs.container.scrollTop = this.refs.container.scrollHeight;
}
}
下面是一个很好的参考反应周期挂钩:http://busypeoples.github.io/post/react-component-lifecycle/
把这个'this.refs.container.scrollTop = this.refs.container.scrollHeight;'在componentDidMount中不起作用 –
你在列表中渲染什么?例如。在componentDidMount期间,scrollHeight可能仍然为零,因为图像尚未加载并且不占用容器中的空间。 – Matti
图片和文字。 –
使用这样的事情 加在列表
<div ref="blankdiv"></div>
然后在每一个componentDidMount
滚动这个div在屏幕
this.refs.blankdiv.scrollIntoView()
所以,当你想在添加一个新的项目它向下滚动网页...?我建议在UX中添加一个新按钮,以允许用户在需要时向下滚动。 – camou
@camou在whatssap的味精,你看到一个按钮来做到这一点? –
不,但是当我在iOS9.2上滚动时,WhatsApp不会强迫我停下来。那么,您何时想要向下滚动,何时出现新消息或用户在最后几秒内停止滚动? – camou