所以,我在 React 中的自动滚动有一个问题,我需要在我的消息可见时添加自动滚动,当用户提交自己的数据并且一切正常时,页面顶部会出现一条消息。然后他需要移动到页面顶部,当然,使用自动滚动。
const valMessageRef = useRef<HTMLDivElement | null>(null);
const errorLabelRef = () => scrollToRef(validationMessageRef);
const scrollToRef = (ref: RefObject<HTMLDivElement>) => {
if (ref.current) {
window.scrollTo(0, ref.current.offsetTop);
}
};
useEffect(() => {
errorLabelRef();
}, [validationMessageRef.current]);
return (
<div className="w-100">
{screenType === "success" && (
<div className="ew-form-group_message" ref={validationMessageRef}>
<p className="ew-form-group__val__messages">
<span className="ew-form-group__val__message">{translation.messages.SUCCESS}</span>
</p>
</div>
)}
</div>
....
我创建了一个小的JSFiddle:
https://jsfiddle.net/z64yetpa/5/
class TodoApp extends React.Component {
constructor(props) {
super(props)
this.state = {
showMessage: false
}
this.handleSend = this.handleSend.bind(this);
}
scrollTo() {
window.scrollTo({ left: 0, top: this.myRef.current.offsetTop, behavior: 'smooth' })
}
componentDidMount(){
this.myRef = React.createRef()
}
handleSend(){
this.setState({showMessage:true}, () => this.scrollTo());
}
render() {
const {showMessage} = this.state;
return (
<div className="parent">
{showMessage &&
<div className="upper" ref={this.myRef}>
Hello, scroll to me automatically
</div>
}
<div>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
</div>
<button onClick={this.handleSend}>Send</button>
</div>
)
}
}
ReactDOM.render(<TodoApp />, document.querySelector("#app"))
单击时,您将被重定向到顶部。