簡體   English   中英

反應滾動到文本區域的底部

[英]React Scroll to bottom of textarea

我將文本附加到 textarea 然后嘗試滾動到底部以保持最新的視圖。 但是,在這樣做時,我似乎使瀏覽器崩潰/內存不足。 任何人都可以幫助優化此代碼嗎?

//Appending text and calling scroll function
this.setState({ transcriptText: this.state.transcriptText + resp.log })
this.scrollToBottom();

//Textarea
<TextArea
  ref={textLog => this.textLog = textLog}
  autosize={{ minRows: 10, maxRows: 15 }}
  value={this.state.transcriptText}
>
</TextArea>

//Scrolling
scrollToBottom = () => {
    const textLogContainer = ReactDOM.findDOMNode(this.textLog);
    if(textLogContainer){
        textLogContainer.scrollTop = textLogContainer.scrollHeight;
    }
};

滿的

componentDidMount() {
    const socket = io.connect(process.env.REACT_APP_API_URL, { transports: ['websocket'] });
    socket.emit('onboarding', { id: uploadId });
    socket.on('transcript_log', function (resp) {
        this.setState({ transcriptText: this.state.transcriptText + resp.log })
        this.scrollToBottom();
    }.bind(this));
}

謝謝

使用較新的React.createRef()並使用componentDidUpdate()作為觸發器更容易:

constructor(props) {
    super(props);

    this.textLog = React.createRef();
}

componentDidUpdate() {
    this.textLog.current.scrollTop = this.textLog.current.scrollHeight;
}

render() {
    return(
        <textarea ref={this.textLog} value={this.state.transcriptText} />
    );
}

當您有 ref 時,您不需要執行ReactDOM.findDOMNode ,將其更改為僅檢查 ref 是否為空,然后更改scrollTop

像這樣

scrollToBottom = () => {
    if(this.textLog){
        this.textLog.scrollTop = this.textLog.scrollHeight;
    }
};

我掙扎了很長時間才弄清楚這一點。 我有一個 ReactJS 應用程序,它從機器上運行的服務讀取日志文件,我希望最新的日志消息滾動到視圖中。 這是我使用 React Hooks 的 LogFileTextBox 控件的一個比較完整的示例:

import { Row } from "react-bootstrap";
import { Col } from "react-bootstrap";
import { Container } from "react-bootstrap";
import { useRef, useEffect } from "react";

const LogFileTextBox = (props) => {
  const logText = props.logText;
  const logFileName = props.logFileName;
  const textArea = useRef();
  
  // After render, this scrolls the textArea to the bottom.
  useEffect(() => {
    const area = textArea.current;
    area.scrollTop = area.scrollHeight;
  });

  return (
    <div>
      <Container fluid>
        <Row>&nbsp;</Row>
        <Row>&nbsp;</Row>
        <Row>
          <Col></Col>
          <Col>
            <h6>Current Log: {logFileName}</h6>
          </Col>
          <Col></Col>
        </Row>
        <Row>
          <Col>
            <textarea                 
              value={logText}
              readOnly={true}
              ref={textArea}    // This links the useRef() hook to this object in the dom
            />
          </Col>
        </Row>
      </Container>
    </div>
  );
};

export default LogFileTextBox;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM