useRef() 钩住自定义组件 [英] useRef() Hook on a custom component
问题描述
我正在尝试创建一个导航栏,当用户单击其中一个链接时,页面会滚动到某个部分.在上面的代码中,每个元素都是我页面的一部分:
<主logo ref={mainLogoRef}/><销售参考={salesRef}/><介绍ref={introductionRef}/><博客引用={blogRef}/><页脚/>
'refs' 被声明如下,使用 useRef 钩子:
const mainLogoRef = useRef(null)const salesRef = useRef(null)const 介绍Ref = useRef(null)const blogRef = useRef(null)
我用来滚动的功能如下:
const scrollToRef = ref =>{window.scrollTo({ top: ref.current.offsetTop, 行为: "smooth" })}
问题是当前"键总是未定义的.当我做这样的事情时:
<销售/><div>或
<销售/><部门>
一切正常.我假设 'ref' 仅适用于 html 'pure' 标签.有没有办法在自定义组件中使用useRef"钩子?
免责声明:对不起,英语不好,我不是母语人士.
解决方案 在自定义组件上,ref
需要 转发.
示例如下:
//在 Sales.js 中const Sales = (props, ref) =>(<div ref={ref}>//将 ref 分配给实际的 DOM 元素,即 div/* 你想在这里渲染的任何东西 */
)导出默认 React.forwardRef(Sales);
这是因为 ref
(通常)是对 DOM 元素的引用.一个 React 组件可以渲染多个 DOM 元素,所以你需要明确 ref
应该分配到哪里.
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.
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.
这篇关于useRef() 钩住自定义组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!