简体   繁体   English

React - 菜单下拉动态绝对 position

[英]React - Menu dropdown dynamic absolute position

I am new to React and I am trying to translate my old website that was vanillaJS into ReactJS.我是 React 新手,我正在尝试将我的旧网站 vanillaJS 翻译成 ReactJS。

I have a button that should trigger a dropdown to open.我有一个按钮应该触发下拉菜单打开。

<button 
   type="button" 
   onClick={() => setMenuOpen(!isMenuOpen)} 
   ref={menuBtn}>menu</button>

and lower down in the DOM tree, I have:在 DOM 树的下方,我有:

{
isMenuOpen ?
  <nav style={{
     top: menuBtn.current.offset().top + menuBtn.current.outerHeight(),
     left: menuBtn.current.offset().left + (menuBtn.current.outerWidth() / 2)
  }}>
    ...
  </nav>
: null
            }

And

const [isMenuOpen, setMenuOpen] = useState(false)
let menuBtn = React.createRef()

at the start of my function Component .在我的function Component的开头。

But it does not work.但它不起作用。

I get:我得到:

TypeError: Cannot read property 'offset' of null

Also, I think that even if this was working, it would not be responsive.另外,我认为即使这有效,它也不会响应。 If the user click on the button, then resize the window, it will not follow where the button is.如果用户单击按钮,然后调整 window 的大小,它将不会跟随按钮所在的位置。

Thank you !谢谢 !

The answer was the use .current.getBoundingClientRect() instead of .current.offset()答案是使用.current.getBoundingClientRect()而不是.current.offset()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM