面试题答案
一键面试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
方法在更新完成后,将输入框的滚动位置恢复为之前保存的值。这样用户在提交表单后,输入框的滚动位置得以保留,方便继续编辑。