因此,我在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>
....
答案 0 :(得分:1)
我创建了一个小的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"))
点击后,您将重定向到顶部。