React - 滚动到 flex 容器的底部而不滚动整个页面

React - scrolling to the bottom of a flex container without scrolling the whole page

我正在使用 React 并尝试构建一个类似聊天的 Facebook - 右栏向下滚动并有一个主题列表,中间栏有主题内容并向下滚动。

我使用 flex 进行了所有设置,但我坚持让中间列默认滚动到底部(因为我想查看最新的聊天消息)。这是实际容器的片段(我使用的是 React bootstrap):

 <Row  >
    <Col ref={ (node) => { this.cont = node }}>
                                {this._buildThread()};
   </Col>
</Row>

这是我的 ComponentDidMount 的片段:

componentDidMount() {
    MessageStore.addChangeListener(this._onChange);
    MessageService.getThread(this.props.id, 1000, 1, false);

    this.cont.scrollTop = this.cont.scrollHeight;

}

其中 cont 是保存我的消息的容器 div 的引用。然而什么也没有发生——它不滚动,如果我在设置后查看 node.scrollTop,它仍然为 0——似乎是不可变的。 任何帮助将非常感激。谢谢!

您什么时候触发包含的代码?要在渲染时滚动到底部,我会写类似下面的内容,在 componentDidMount 中调用 triggerScroll:

class App extends React.Component {
    componentDidMount () {
        this.triggerScroll();
    }

    triggerScroll () {
        this.cont.scrollTop = this.cont.scrollHeight;
    }

    render () {
        return (
            <div>
                <div className='containerIWantToScroll' ref={ (node) => { this.cont = node } }>
                    Content
                </div>
            </div>
        )
    }
}

不确定您 CSS 的详细信息,但我遇到了类似的问题。我的解决方案是确保元素本身会滚动而不是它的容器:

.containerIWantToScroll {
    overflow-y: auto;
}

如果元素的容器扩展以适合元素,则该元素将不会滚动,因此其 scrollTop 值始终为零。