【问题标题】:Cannot scroll to the bottom of a div using React.js refs无法使用 React.js refs 滚动到 div 的底部
【发布时间】:2019-01-03 18:26:39
【问题描述】:

您好,我正在构建一个应用程序,其中有一个列表,并且在组件安装时我总是想转到列表的底部。

这是我的render 方法

<div className="message-placeholder" 
                 ref={this.myRef}>
                <List
                    dataSource={this.state.data}
                    renderItem={item => (
                    <List.Item key={item.id}>
                        <List.Item.Meta
                            avatar={<Avatar style={{ backgroundColor: '#08c' }} icon="user" />}
                            title={<a href="#">{item.name}</a>}
                            description={item.message}
                        />
                    </List.Item>
                    )}
                >
                    {this.state.loading && this.state.hasMore && <Spin className="demo-loading" />}
                </List>

在我的构造函数中,我创建了一个新的 ref。像这样

constructor(props){
        super(props);
        this.myRef = React.createRef();

我的 CSS 看起来像这样。

.message-placeholder {
    height: 300px;
    overflow-y: scroll;
    -webkit-overflow-scrolling: touch;
}

现在每次组件更新时,我都会尝试转到列表底部。这就是我的做法。

componentDidUpdate() {
        this.scrollToBottom();
    }

scrollToBottom = () => {
        this.myRef.scrollIntoView({block: 'end', behavior: 'smooth'});
    }

但是,这不起作用我收到以下错误_this.myRef.scrollIntoView is not a function

请有人帮我解决这个问题。提前致谢。 :)

【问题讨论】:

    标签: javascript reactjs css-selectors


    【解决方案1】:

    您可以使用它来滚动特定部分到bottom

    document.querySelector(".message-placeholder").scrollTo(0,document.querySelector(".message-placeholder").scrollHeight);
    

    并且scrollIntoView 没有很好的浏览器兼容性检查这个 https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView#Browser_compatibility.

    【讨论】:

      【解决方案2】:

      我建议使用像 react-scroll 这样的专用包

      【讨论】:

        【解决方案3】:
        <div className="message-placeholder" ref={(ref) => { this.myRef = ref; }}>
        

        【讨论】:

        • 你能提供更多关于代码的细节吗?
        猜你喜欢
        • 1970-01-01
        • 2017-06-07
        • 2018-03-19
        • 1970-01-01
        • 2015-11-20
        • 2017-04-05
        • 2012-07-13
        • 2010-09-21
        相关资源
        最近更新 更多