MST

星途 面试题库

面试题:React中getSnapshotBeforeUpdate在表单场景的应用

假设你正在开发一个包含输入框的表单,用户输入内容后提交。在提交后要保留输入框之前的滚动位置,以便用户继续编辑。请阐述如何使用getSnapshotBeforeUpdate方法来实现这一场景,并简单写出关键代码。
27.1万 热度难度
前端开发React

知识考点

AI 面试

面试题答案

一键面试

1. 使用getSnapshotBeforeUpdate方法实现思路

在 React 组件中,getSnapshotBeforeUpdate方法在更新发生之前被调用,此时 DOM 尚未更新。我们可以利用这个方法获取输入框当前的滚动位置,然后在更新完成后,将滚动位置恢复。

2. 关键代码示例

import React, { Component } from 'react';

class FormWithScrollPreservation extends Component {
    constructor(props) {
        super(props);
        this.inputRef = React.createRef();
        this.state = {
            inputValue: '',
            scrollPosition: 0
        };
    }

    handleSubmit = (e) => {
        e.preventDefault();
        // 模拟提交操作
        console.log('Submitted:', this.state.inputValue);
        // 这里可以进行实际的提交逻辑,比如发送 API 请求等
        // 提交后更新输入框内容(假设清空)
        this.setState({
            inputValue: ''
        });
    }

    getSnapshotBeforeUpdate(prevProps, prevState) {
        if (prevState.inputValue!== this.state.inputValue) {
            return this.inputRef.current.scrollTop;
        }
        return null;
    }

    componentDidUpdate(prevProps, prevState, snapshot) {
        if (snapshot!== null) {
            this.inputRef.current.scrollTop = snapshot;
        }
    }

    render() {
        return (
            <form onSubmit={this.handleSubmit}>
                <textarea
                    ref={this.inputRef}
                    value={this.state.inputValue}
                    onChange={(e) => this.setState({ inputValue: e.target.value })}
                />
                <button type="submit">提交</button>
            </form>
        );
    }
}

export default FormWithScrollPreservation;

在上述代码中:

  • getSnapshotBeforeUpdate方法在输入框内容发生变化(即将更新)时,获取当前输入框的滚动位置scrollTop
  • componentDidUpdate方法在更新完成后,将输入框的滚动位置恢复为之前保存的值。这样用户在提交表单后,输入框的滚动位置得以保留,方便继续编辑。