useRef() Hook on a custom component

白昼怎懂夜的黑 提交于 2020-12-03 15:48:54

问题


I'm trying do create a Navigation Bar that when the user click on one of the links, the page scrolls to some section. In the code above, each element is a section of my page:

    <Navbar scrollFunc={scrollToRef} />      
    <Mainlogo ref={mainLogoRef} />
    <Sales  ref={salesRef} />
    <Introduction ref={introductionRef} />
    <Blog ref={blogRef} />
    <Footer />

The 'refs' was declares as folowing, using the useRef hook:

  const mainLogoRef = useRef(null)
  const salesRef = useRef(null)
  const introductionRef = useRef(null)
  const blogRef = useRef(null)

The function i'm using to scroll is the folowing:

  const scrollToRef = ref => {
    window.scrollTo({ top: ref.current.offsetTop, behavior: "smooth" })
  }

The thing is that the 'current' key is always undefined. When i do something like that:

<div ref={salesRef}> <Sales  /><div>

or

<section ref={salesRef}> <Sales  /><section>

Things works just fine. I'm assuming that 'ref' works only on html 'pure' tags. Is there any way to use 'useRef' hook in a custom component?

disclaimer: Sorry for bad english, i'm not a native speaker.


回答1:


On custom components, ref needs to be forwarded.

An example would be like:

// inside Sales.js
const Sales = (props, ref) => (
  <div ref={ref}> // assigns the ref to an actual DOM element, the div
    /* anything you want to render here */
  </div>
)

export default React.forwardRef(Sales);

This is because ref is (usually) a reference to a DOM element. A React Component can renders multiple DOM element, so you need to be explicit about where the ref should be assigned to.



来源:https://stackoverflow.com/questions/61192450/useref-hook-on-a-custom-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!