【问题标题】:useRef() Hook on a custom componentuseRef() 挂钩自定义组件
【发布时间】:2020-07-26 06:45:03
【问题描述】:

我正在尝试创建一个导航栏,当用户单击其中一个链接时,页面会滚动到某个部分。在上面的代码中,每个元素都是我页面的一部分:

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

'refs' 被声明为如下,使用 useRef 钩子:

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

我用来滚动的功能如下:

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

问题是“当前”键始终未定义。当我做这样的事情时:

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

或

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

一切正常。我假设 'ref' 仅适用于 html 'pure' 标签。有没有办法在自定义组件中使用“useRef”挂钩?

免责声明:抱歉英语不好,我不是母语人士。

【问题讨论】:

    标签: javascript reactjs react-hooks use-ref


    【解决方案1】:

    在自定义组件上,ref 需要为 forwarded。

    举个例子:

    // 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);
    

    这是因为ref(通常)是对 DOM 元素的引用。一个 React 组件可以渲染多个 DOM 元素,所以你需要明确 ref 应该分配到哪里。

    【讨论】:

    • 我相信您回答的要点是正确的,尽管我认为组件函数的签名可能应该是 const Sales = ({ ref, ...props }) =&gt; 因为函数组件的第一个参数始终是 props 对象,而 ref 是一个道具。
    • 直接取自react docs "注意:第二个 ref 参数仅在您使用 React.forwardRef 调用定义组件时存在。常规函数或类组件不接收 ref 参数,并且 ref在道具中也不可用。”
    • 工作得很好。谢谢!
    • 感谢@Jackyef 的澄清和文档链接。我忽略了在您的解决方案中看到 React.forwardRef 调用。
    猜你喜欢
    • 2022-11-23
    • 2021-04-27
    • 1970-01-01
    • 2022-11-01
    • 2020-01-29
    • 2021-03-14
    • 2020-04-07
    • 2019-11-27
    • 2021-12-07
    相关资源
    最近更新 更多