【发布时间】:2021-04-16 17:23:12
【问题描述】:
我正在使用一个组件库,它呈现嵌套在多个 div 元素中的 input 字段
<ComponentLibrary />
这个组件库渲染一棵类似于下面的树:
<div className={outerDiv}>
<div>
<input type="text" /> // This the element I'm trying to access
</div>
</div>
我构建了一个自定义组件,它包装了ComponentLibrary,如下所示:
<MyCustomComponent>
<ComponentLibrary />
</MyCustomComponent>
我无权修改组件库,但我需要访问它在我的组件中的 input 字段。
const MyCustomComponent = (props) => {
const inputRef = useRef();
return (
{React.cloneElement(props.children, {
ref: inputRef // This ofcourse references the 'outerDiv'
}}
);
}
一些可能的相关说明,当我console.log(props.children)。虽然组件是 react 元素,但类型是前向引用。
> 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?
【问题讨论】:
-
你使用的组件库是什么?
-
@BasvanderLinden 我正在使用我公司的一个团队构建的内部组件库,该团队独立于我的工作。
-
ComponentLibrary的文档接口是什么?最好使用它而不是使用 React 内部结构,这种方式可能会在下次ComponentLibrary的实现更新时中断。
标签: javascript reactjs