javascript - react : How to use refs in a function component that I have no control over (i. e。从图书馆)

标签 javascript reactjs react-hooks

我不敢相信我找不到答案,所以如果我错了,请指出我正确的方向。

我正在尝试做一些简单的事情:

我包含的库中有一个功能组件。

我需要引用它。

至关重要的是,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 ,但在这种情况下不能,因为我不能直接修改库的代码。

我确实看到了thisthis但不认为两者都适用于我。

有任何想法吗?

最佳答案

你不能直接。如果组件不是这样编写的,就没有钩子(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/

相关文章:

javascript - 如何逐行获取html表格值并对值进行一些计算?

javascript - 我在输入类型文件中的 onChange 之后得到未命名状态 - ReactJS

javascript - 在 Redux 中,状态实际上存储在哪里?

javascript - 如何修复 "... is not a function"错误?

javascript - gwt编译器找不到入口点类

javascript - 即使手动将 readonly 属性设置为 false,文本框也会在回发时变为只读

javascript - Raphael JS 失败

javascript - 在 React 中测试文本值

javascript - 如何使用react hooks在其中一个复选框上使用onChange事件来操作map函数内部的DOM

reactjs - useReducer hook,如何对 Action 进行类型检查?