我不敢相信我找不到答案,所以如果我错了,请指出我正确的方向。
我正在尝试做一些简单的事情:
我包含的库中有一个功能组件。
我需要引用它。
至关重要的是,React 是这样说的:
Ref forwarding lets components opt into exposing any child component’s ref as their own.
不幸的是,这个库组件没有选择使用
forwardRef
。 .获取此元素的引用的正确方法是什么?
3rd party library component in question看起来像这样(简化):
function OutboundLink(props) {
return (
<a {...props}
...
/>
)
}
我的组件看起来像这样:
function MyComp(props) {
const ref = useRef(null)
return (
<OutboundLink ref={ref} {...props} >
{children}
</OutboundLink>
)
}
但是我收到了关于无法将 refs 传递给函数组件的错误。通常我会换成
forwardRef
,但在这种情况下不能,因为我不能直接修改库的代码。我确实看到了this和 this但不认为两者都适用于我。
有任何想法吗?
最佳答案
你不能直接。如果组件不是这样编写的,就没有钩子(Hook)可以让你进入。
我认为你最好的选择是包装组件,捕获一个 ref,然后使用 DOM 方法深入到它的子组件中。
const wrapperRef = useRef(null)
const innerRef = useRef(null)
useEffect(() => {
if (wrapperRef.current) {
innerRef.current = wrapperRef.current.querySelector('a')
// innerRef.current is now the first <a> tag inside <OutboundLink>
}
})
return <div>
<div ref={wrapperRef}>
<OutboundLink {...props}>
{children}
</OutboundLink>
</div>
</div>
Codepen example (查看控制台)
但实际上,这有点骇人听闻。您应该使用可以更好地处理此问题的组件。看看自己从头开始编写这个组件有多难。这可能是微不足道的,而且值得。
关于javascript - react : How to use refs in a function component that I have no control over (i. e。从图书馆),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61197847/