Javascript React-访问组件库';s子DOM

Javascript React-访问组件库';s子DOM,javascript,reactjs,Javascript,Reactjs,我正在使用一个组件库,它呈现嵌套在几个div元素中的input字段 <ComponentLibrary /> 我没有修改组件库的权限,但我需要访问组件中的input字段 const MyCustomComponent = (props) => { const inputRef = useRef(); return ( {React.cloneElement(props.children, { ref: inputRef // This ofcou

我正在使用一个组件库,它呈现嵌套在几个
div
元素中的
input
字段

<ComponentLibrary />
我没有修改组件库的权限,但我需要访问组件中的
input
字段

const MyCustomComponent = (props) => {
  const inputRef = useRef();

  return (
    {React.cloneElement(props.children, {
      ref: inputRef // This ofcourse references the 'outerDiv'
    }}
  );
}
一些可能的相关注释,当I
console.log(props.children)
时。当组件是react元素时,类型是forward ref

> children:
  $$typeof: Symbol(react.element)
  ref: null
  > type: {$$typeof: Symbol(react.forward_ref)}

以下是我的几次尝试:

{React.Children.map(props.children, child => {
   console.log(child) // Only logs the Component element. No reference of DOM nodes
}
我得到的最接近的方法是使用我在上面第四个代码块中创建的
inputRef

console.log(inputRef.current)
// Logs `outerDiv` element

console.log(inputRef.current.children[0]?.children[1]?.children[1])
// Returns the right element, but an absolute mess. Is this my best solution?

我可能在这里理解错误,但通过阅读您的问题,我假设
ComponentLibrary
看起来像这样:

const ComponentLibrary = React.forwardRef((props, ref) => (
  <div ref={ref}>
    <div>
      <input type="text" />
    </div>
  </div>
));
在复制
MyCustomComponent
设置时

const MyCustomComponent = (props) => {
  const inputRef = useRef();

  useEffect(() => {
    console.log(inputRef.current); 
  });

  return React.cloneElement(props.children, {
    ref: inputRef,
  });
};
inputRef.current
注销以下元素:

<div>
  <div>
    <input type="text" />
  </div>
</div>

您使用的组件库是什么?@BasvanderLinden我使用的是一个内部组件库,它由我公司的一个团队构建,独立于我的团队工作。组件库的文档界面是什么?最好使用它,而不是使用React内部构件,这种方式可能会在下一次
组件库
的实现更新时中断。这是一种更好的解决方案。非常感谢。我真的没想过要这么做!因此,由于ComponentLibrary是forwardedRef。有没有更好的/首选的方式来访问它或它的孩子们,而不是
道具。孩子们
?另外,谢谢你的支持。我意识到,对于一行解决方案,这是一个很大的帖子。但是,您分解了各种代码块,或者重申了我提供的信息,或者给出了我所问问题的上下文,这非常有帮助。所以,为你的耐心和细节干杯,我不确定有没有更好的方法。如果在函数参数
({children})
中使用解构,而不是
(props)
,则可以使用
子类
,但这是一个非常微不足道的更改。您还可以在
MyCustomComponent
内部直接渲染
ComponentLibrary
,而无需使用道具,并直接附加ref。但是,与使用
子组件相比,在包装其他类似类型的组件方面,您将失去一些灵活性。有关从子元素获取dom节点的方法的概述,请参见。。。。。。
$$typeof: Symbol(react.forward_ref)
const MyCustomComponent = (props) => {
  const inputRef = useRef();

  useEffect(() => {
    console.log(inputRef.current); 
  });

  return React.cloneElement(props.children, {
    ref: inputRef,
  });
};
<div>
  <div>
    <input type="text" />
  </div>
</div>
console.log(inputRef.current.querySelector('input[type="text"]'));