Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 加载项目时,componentDidUpdate滚动到底部_Javascript_Reactjs_Ecmascript 6 - Fatal编程技术网

Javascript 加载项目时,componentDidUpdate滚动到底部

Javascript 加载项目时,componentDidUpdate滚动到底部,javascript,reactjs,ecmascript-6,Javascript,Reactjs,Ecmascript 6,我有一个列表,我想滚动到底部,我有我的组件编码如下 class Msg extends Component { componentDidUpdate() { if(this.container){ this.container.scrollTop = this.container.scrollHeight } } render() { return( <div re

我有一个列表,我想滚动到底部,我有我的组件编码如下

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>
        )
    }
}
class Msg扩展组件{
componentDidUpdate(){
if(这个容器){
this.container.scrollTop=this.container.scrollHeight
}
}
render(){
返回(
)
}
}
成功了。但问题是,每次组件重新加载时,它都会滚动。Msg有很多子组件,触发子组件的状态会导致Msg组件再次渲染,如何解决这个问题

要像普通用户一样解释它,请执行以下操作:


用户向上滚动列表,然后单击某个下拉列表,触发componentDidUpdate,导致滚动到底部。

要在呈现组件时第一次滚动到底部,应使用
componentDidMount
lifecycle挂钩

如果希望列表在每次添加元素时滚动,可以像现在一样使用
componentdiddupdate
hook,但不要每次都操作scrolltop,而是检查渲染的项目数是否已更改。现在,您可以在每次组件更新时设置滚动顶部

componentDidUpdate
获取previous props和previous state作为参数,因此您可以编写如下内容:

componentDidUpdate(prevProps, prevState) {
    if (this.props.items.length > prevProps.items.length) {
        this.refs.container.scrollTop = this.refs.container.scrollHeight;
    }
}
这里有一个关于reacts生命周期挂钩的很好的参考:

使用类似的东西 在列表末尾添加一个空白div

然后在每个
componentDidMount
屏幕中滚动此div


this.refs.blankdiv.scrollIntoView()

那么,您希望它什么时候向下滚动。。。当添加新项目时?我建议在用户体验中添加一个新按钮,允许用户在需要时向下滚动。@camou在whatssap的msg中,你看到一个按钮可以这样做吗?没有,但是当我在iOS9.2上向上滚动时,WhatsApp不会强迫我向下滚动。因此,当您想要向下滚动时,当出现新消息时,或者当用户在最后几秒钟内停止向上滚动时,请将此
this.refs.container.scrollTop=this.refs.container.scrollHeight在componentDidMount中它将不起作用您在列表中呈现的是什么?例如,对于图像,在componentDidMount期间,滚动高度可能仍然为零,因为图像尚未加载,并且不会占用容器中的空间。图像和文本。您在componentDidMount中获得了一些滚动高度,还是仅为零?如果使用setTimeout延迟获取滚动高度,您会得到一些信息吗?(仅用于调试。在没有超时的情况下对滚动进行黑客攻击可能会导致更多的麻烦)