簡體   English   中英

反應模態滾動到頂部

[英]React modal scroll to top

我的反應應用程序中有一個長形式的模式。 因此,當我提交表單時,我會在表單頂部顯示來自服務器的驗證消息。 所以用戶必須滾動到頂部才能查看消息。 所以我想在消息出現時自動滾動到頂部。 所以我在提交處理程序 function 中添加了以下代碼。但它不起作用。

setAddModalErrorMsg([{ msg: res.data.msg, type: "error" }])
                    window.scrollTo({
                        top: 0,
                        left: 0,
                        behavior: "smooth"
                      });

其他答案顯示了如何將模式滾動到頂部,這是實現此目的的普遍接受的方式,不過,我想向您展示如何將“消息”滾動到視圖中,無論它是在頂部還是不是。

您還需要創建一個指向顯示消息的位置的ref ,並使用scrollIntoView功能將模態滾動到您的驗證消息。

import React, { useRef } from 'react';

const Modal = () => {
  const validationMessageRef = useRef();

  const setAddModalErrorMsg = () => {
    // scrolls the validation message into view, and the block: 'nearest' ensures it scrolls the modal and not the window
    validationMessageRef.current?.scrollIntoView({ block:'nearest' });
  }

  return (
    <div>
      <div ref={validationMessageRef}>
        // your validation message is displayed here
      </div>

      // rest of your modal content here
    </div>

  )
}

您正在嘗試滾動 window,但很可能您的 window 已經在頂部,這是您需要向上滾動的模態元素。

為此,我將創建對模態元素的引用,然后在您的 function 中通過 ref 滾動模態元素,因此如下所示:

import React, {useRef} from 'react';

const Modal = (props) => {
  // use the useRef hook to store a reference to the element
  const modalRef = useRef();
  
  const setAddModalErrorMsg = () => {
    // check the ref exists (it should always exist, it's declared in the JSX below), and call a regular javascript scrollTo function on it
    modalRef.current?.scrollTo({x: 0, y: 0, animated: false});
  }
  
  // see here we create a reference to the div that needs scrolled
  return (
    <div ref={modalRef}>
     { // your modal content }
    </div>
  )

}

要自動滾動到頂部,我們可以使用以下代碼:

  constructor(props) {
    super(props)
    this.myRef = React.createRef()   // Create a ref object 
    }

在 setAddModalErrorMsg 之后添加 scrollTo function。

 setAddModalErrorMsg([{ msg: res.data.msg, type: "error" }])
    this.myRef.current.scrollTo(0, 0);

 <div ref={this.myRef}></div> 

將 ref 屬性附加到頂級 dom 元素

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM