development

반응에서 아래로 스크롤하는 방법은 무엇입니까?

big-blog 2020. 10. 6. 08:27
반응형

반응에서 아래로 스크롤하는 방법은 무엇입니까?


채팅 시스템을 구축하고 창에 들어갈 때와 새 메시지가 들어올 때 자동으로 하단으로 스크롤하고 싶습니다. React에서 컨테이너 하단으로 자동으로 스크롤하는 방법은 무엇입니까?


Tushar가 언급했듯이 채팅 하단에 더미 div를 유지할 수 있습니다.

render () {
  return (
    <div>
      <div className="MessageContainer" >
        <div className="MessagesList">
          {this.renderMessages()}
        </div>
        <div style={{ float:"left", clear: "both" }}
             ref={(el) => { this.messagesEnd = el; }}>
        </div>
      </div>
    </div>
  );
}

그런 다음 구성 요소가 업데이트 될 때마다 스크롤합니다 (예 : 새 메시지가 추가되면 상태가 업데이트 됨).

scrollToBottom = () => {
  this.messagesEnd.scrollIntoView({ behavior: "smooth" });
}

componentDidMount() {
  this.scrollToBottom();
}

componentDidUpdate() {
  this.scrollToBottom();
}

여기 에서는 표준 Element.scrollIntoView 메서드를 사용하고 있습니다.


사용하지 마세요 findDOMNode

class MyComponent extends Component {
  componentDidMount() {
    this.scrollToBottom();
  }

  componentDidUpdate() {
    this.scrollToBottom();
  }

  scrollToBottom() {
    this.el.scrollIntoView({ behavior: 'smooth' });
  }

  render() {
    return <div ref={el => { this.el = el; }} />
  }
}

React.createRef() 메서드 와 일치하도록 답변을 업데이트하고 싶지만 기본적으로 동일 current하며 생성 된 참조 속성을 염두에 두십시오 .

class Messages extends React.Component {

  messagesEndRef = React.createRef()

  componentDidMount () {
    this.scrollToBottom()
  }
  componentDidUpdate () {
    this.scrollToBottom()
  }
  scrollToBottom = () => {
    this.messagesEnd.current.scrollIntoView({ behavior: 'smooth' })
  }
  render () {
    const { messages } = this.props
    return (
      <div>
        {messages.map(message => <Message key={message.id} {...message} />)}
        <div ref={this.messagesEndRef} />
      </div>
    )
  }
}

최신 정보:

이제 후크를 사용할 수 있으므로 useRefuseEffect후크 사용을 추가하기 위해 답변을 업데이트하고 있습니다 . 실제 수행하는 마법 (React refs 및 scrollIntoViewDOM 메서드)은 동일하게 유지됩니다.

import React, { useEffect, useRef } from 'react'

const Messages = ({ messages }) => {

  const messagesEndRef = useRef(null)

  const scrollToBottom = () => {
    messagesEndRef.current.scrollIntoView({ behavior: "smooth" })
  }

  useEffect(scrollToBottom, [messages]);

  return (
    <div>
      {messages.map(message => <Message key={message.id} {...message} />)}
      <div ref={this.messagesEndRef} />
    </div>
  )
}

또한 https://codesandbox.io/s/scrolltobottomexample-f90lz 동작을 확인하려면 (매우 기본적인) 코드 샌드 박스를 만들었습니다.


@enlitement 덕분에

사용을 피해야 합니다. 구성 요소를 추적 findDOMNode하는 refs사용할 수 있습니다.

render() {
  ...

  return (
    <div>
      <div
        className="MessageList"
        ref={(div) => {
          this.messageList = div;
        }}
      >
        { messageListContent }
      </div>
    </div>
  );
}



scrollToBottom() {
  const scrollHeight = this.messageList.scrollHeight;
  const height = this.messageList.clientHeight;
  const maxScrollTop = scrollHeight - height;
  this.messageList.scrollTop = maxScrollTop > 0 ? maxScrollTop : 0;
}

componentDidUpdate() {
  this.scrollToBottom();
}

참고:


refs를 사용 하여 구성 요소를 추적 할 수 있습니다 .

ref하나의 개별 구성 요소 (마지막 구성 요소) 를 설정하는 방법을 알고 있다면 게시하십시오!

저에게 효과가있는 것은 다음과 같습니다.

class ChatContainer extends React.Component {
  render() {
    const {
      messages
    } = this.props;

    var messageBubbles = messages.map((message, idx) => (
      <MessageBubble
        key={message.id}
        message={message.body}
        ref={(ref) => this['_div' + idx] = ref}
      />
    ));

    return (
      <div>
        {messageBubbles}
      </div>
    );
  }

  componentDidMount() {
    this.handleResize();

    // Scroll to the bottom on initialization
    var len = this.props.messages.length - 1;
    const node = ReactDOM.findDOMNode(this['_div' + len]);
    if (node) {
      node.scrollIntoView();
    }
  }

  componentDidUpdate() {
    // Scroll as new elements come along
    var len = this.props.messages.length - 1;
    const node = ReactDOM.findDOMNode(this['_div' + len]);
    if (node) {
      node.scrollIntoView();
    }
  }
}

  1. 메시지 컨테이너를 참조하십시오.

    <div ref={(el) => { this.messagesContainer = el; }}> YOUR MESSAGES </div>
    
  2. 메시지 컨테이너를 찾고 scrollTop속성을 동일하게 만드십시오 scrollHeight.

    scrollToBottom = () => {
        const messagesContainer = ReactDOM.findDOMNode(this.messagesContainer);
        messagesContainer.scrollTop = messagesContainer.scrollHeight;
    };
    
  3. componentDidMount및에서 위의 메서드를 호출합니다 componentDidUpdate.

    componentDidMount() {
         this.scrollToBottom();
    }
    
    componentDidUpdate() {
         this.scrollToBottom();
    }
    

이것은 내 코드에서 이것을 사용하는 방법입니다.

 export default class StoryView extends Component {

    constructor(props) {
        super(props);
        this.scrollToBottom = this.scrollToBottom.bind(this);
    }

    scrollToBottom = () => {
        const messagesContainer = ReactDOM.findDOMNode(this.messagesContainer);
        messagesContainer.scrollTop = messagesContainer.scrollHeight;
    };

    componentDidMount() {
        this.scrollToBottom();
    }

    componentDidUpdate() {
        this.scrollToBottom();
    }

    render() {
        return (
            <div>
                <Grid className="storyView">
                    <Row>
                        <div className="codeView">
                            <Col md={8} mdOffset={2}>
                                <div ref={(el) => { this.messagesContainer = el; }} 
                                     className="chat">
                                    {
                                        this.props.messages.map(function (message, i) {
                                            return (
                                                <div key={i}>
                                                    <div className="bubble" >
                                                        {message.body}
                                                    </div>
                                                </div>
                                            );
                                        }, this)
                                    }
                                </div>
                            </Col>
                        </div>
                    </Row>
                </Grid>
            </div>
        );
    }
}

메시지 끝에 빈 요소를 만들고 해당 요소로 스크롤했습니다. 심판을 추적 할 필요가 없습니다.


react-scrollable-feed 는 사용자가 이미 스크롤 가능한 섹션의 맨 아래에있는 경우 자동으로 최신 요소로 스크롤합니다. 그렇지 않으면 사용자가 동일한 위치에있게됩니다. 나는 이것이 채팅 구성 요소에 매우 유용하다고 생각합니다. :)

여기에 다른 답변은 스크롤 막대가 어디에 있든 상관없이 매번 강제로 스크롤 할 것이라고 생각합니다. 다른 문제 scrollIntoView는 스크롤 가능한 div가 보이지 않으면 전체 페이지를 스크롤한다는 것입니다.

다음과 같이 사용할 수 있습니다.

import * as React from 'react'

import ScrollableFeed from 'react-scrollable-feed'

class App extends React.Component {
  render() {
    const messages = ['Item 1', 'Item 2'];

    return (
      <ScrollableFeed>
        {messages.map((message, i) => <div key={i}>{message}</div>)}
      </ScrollableFeed>
    );
  }
}

특정 height또는max-height

면책 조항 : 나는 패키지의 소유자입니다.


작업 예 :

DOM scrollIntoView메서드를 사용하여 구성 요소를 뷰에 표시 할 수 있습니다.

이를 위해 컴포넌트를 렌더링하는 동안 ref속성을 사용하여 DOM 요소에 대한 참조 ID를 제공하십시오 . 그런 다음 라이프 사이클 scrollIntoView대한 방법 사용하십시오 componentDidMount. 이 솔루션에 대해 작동하는 샘플 코드를 넣는 중입니다. 다음은 메시지가 수신 될 때마다 렌더링되는 구성 요소입니다. 이 컴포넌트를 렌더링하기위한 코드 / 메소드를 작성해야합니다.

class ChatMessage extends Component {
    scrollToBottom = (ref) => {
        this.refs[ref].scrollIntoView({ behavior: "smooth" });
    }

    componentDidMount() {
        this.scrollToBottom(this.props.message.MessageId);
    }

    render() {
        return(
            <div ref={this.props.message.MessageId}>
                <div>Message content here...</div>
            </div>
        );
    }
}

다음 this.props.message.MessageId은 전달 된 특정 채팅 메시지의 고유 ID입니다.props


또 다른 옵션으로 반응 스크롤 구성 요소를 살펴볼 가치가 있습니다.


나는 다음과 같은 방식으로하는 것을 좋아합니다.

componentDidUpdate(prevProps, prevState){
  this.scrollToBottom();
}

scrollToBottom() {
  const {thing} = this.refs;
  thing.scrollTop = thing.scrollHeight - thing.clientHeight;
}

render(){
  return(
    <div ref={`thing`}>
      <ManyThings things={}>
    </div>
  )
}

import React, {Component} from 'react';

export default class ChatOutPut extends Component {

    constructor(props) {
        super(props);
        this.state = {
            messages: props.chatmessages
        };
    }
    componentDidUpdate = (previousProps, previousState) => {
        if (this.refs.chatoutput != null) {
            this.refs.chatoutput.scrollTop = this.refs.chatoutput.scrollHeight;
        }
    }
    renderMessage(data) {
        return (
            <div key={data.key}>
                {data.message}
            </div>
        );
    }
    render() {
        return (
            <div ref='chatoutput' className={classes.chatoutputcontainer}>
                {this.state.messages.map(this.renderMessage, this)}
            </div>
        );
    }
}

thank you 'metakermit' for his good answer, but I think we can make it a bit better, for scroll to bottom, we should use this:

scrollToBottom = () => {
   this.messagesEnd.scrollIntoView({ behavior: "smooth", block: "end", inline: "nearest" });
}

but if you want to scroll top, you should use this:

scrollToTop = () => {
   this.messagesEnd.scrollIntoView({ behavior: "smooth", block: "start", inline: "nearest" });
}   

and this codes are common:

componentDidMount() {
  this.scrollToBottom();
}

componentDidUpdate() {
  this.scrollToBottom();
}


render () {
  return (
    <div>
      <div className="MessageContainer" >
        <div className="MessagesList">
          {this.renderMessages()}
        </div>
        <div style={{ float:"left", clear: "both" }}
             ref={(el) => { this.messagesEnd = el; }}>
        </div>
      </div>
    </div>
  );
}

If you want to do this with React Hooks, this method can be followed. For a dummy div has been placed at the bottom of the chat. useRef Hook is used here.

Hooks API Reference : https://reactjs.org/docs/hooks-reference.html#useref

import React, { useEffect, useRef } from 'react';

const ChatView = ({ ...props }) => {
const el = useRef(null);

useEffect(() => {
    el.current.scrollIntoView({ block: 'end', behavior: 'smooth' });
});

 return (
   <div>
     <div className="MessageContainer" >
       <div className="MessagesList">
         {this.renderMessages()}
       </div>
       <div id={'el'} ref={el}>
       </div>
     </div>
    </div>
  );
}

Full version (Typescript):

import * as React from 'react'

export class DivWithScrollHere extends React.Component<any, any> {

  loading:any = React.createRef();

  componentDidMount() {
    this.loading.scrollIntoView(false);
  }

  render() {

    return (
      <div ref={e => { this.loading = e; }}> <LoadingTile /> </div>
    )
  }
}

참고URL : https://stackoverflow.com/questions/37620694/how-to-scroll-to-bottom-in-react

반응형