Reactjs 将JS自动滚动到容器底部

Reactjs 将JS自动滚动到容器底部,reactjs,Reactjs,我正在尝试制作一个基本的聊天应用程序,用户在其中输入一条消息,然后它就会出现在屏幕上。与普通的消息传递系统一样,我希望滚动条默认位于底部。我已经尝试使用下面的代码来实现这一点 这是沙箱: 以及守则: import React, { Component } from "react"; export default class Messages extends Component { setScroll() { this.messagesEnd.scrollIntoView({ be

我正在尝试制作一个基本的聊天应用程序,用户在其中输入一条消息,然后它就会出现在屏幕上。与普通的消息传递系统一样,我希望滚动条默认位于底部。我已经尝试使用下面的代码来实现这一点

这是沙箱:

以及守则:

import React, { Component } from "react";

export default class Messages extends Component {
  setScroll() {
    this.messagesEnd.scrollIntoView({ behavior: "auto" });
  }

  componentDidMount() {
    this.setScroll();
  }

  componentDidUpdate() {
    this.setScroll();
  }
  render() {
    return this.props.messages.map(message => {
      return (
        <div>
          <h2>{message.message}</h2>
          <div
            style={{ float: "left", clear: "both" }}
            ref={el => {
              this.messagesEnd = el;
            }}
          />
        </div>
      );
    });
  }
}
import React,{Component}来自“React”;
导出默认类消息扩展组件{
setScroll(){
this.messagesEnd.scrollIntoView({behavior:“auto”});
}
componentDidMount(){
这个.setScroll();
}
componentDidUpdate(){
这个.setScroll();
}
render(){
返回此.props.messages.map(message=>{
返回(
{message.message}
{
this.messagesEnd=el;
}}
/>
);
});
}
}

它可以正常工作,但是如果容器外的组件中有滚动条,它也会将滚动条设置到底部。是否有任何方法我只能将容器的滚动条设置为底部(独立于屏幕上的任何其他滚动条)

更新您的
setScroll
以包含
块:“end”
作为
滚动视图的选项:

setScroll() {
    this.messagesEnd.scrollIntoView({ behavior: "auto", block: "end" });
  }

更新您的
setScroll
以包含
块:“end”
作为
滚动视图的选项:

setScroll() {
    this.messagesEnd.scrollIntoView({ behavior: "auto", block: "end" });
  }

你想要达到的目标并不明确。你想要达到的目标也不明确。