React 滚动到文本区域的底部

Ell*_*eve 3 html javascript reactjs

我将文本附加到文本区域,然后尝试滚动到底部以保留最新内容。然而,在这样做时,我似乎使浏览器崩溃/内存不足。谁能帮忙优化这段代码吗?

//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;
    }
};
Run Code Online (Sandbox Code Playgroud)

满的

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));
}
Run Code Online (Sandbox Code Playgroud)

谢谢

Sam*_*Sam 8

使用较新的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} />
    );
}
Run Code Online (Sandbox Code Playgroud)