如何添加对 HTMLCollection 项目的反应引用?

问题描述

我正在尝试访问对 react-markdown 中每个段落/标题的附加引用。但我不知道如何在下面的 c 中添加一个引用。

const children = Array.from(div.children)
children?.forEach((c,i) => {
  // c = <p>...</p> or <h1>...</h1>
  // add ref from useRef to c
})

解决方法

您可以使用 ReactcloneElement(element,propsObject,childrenAray) 克隆一个元素。这会保留来自克隆元素的 key 和 ref 道具。有关更多信息,请访问:https://reactjs.org/docs/react-api.html#clonelement

或者你可以这样做:

const children = Array.from(div.children)
children?.forEach((c,i) => {
  return <c.type {...c.props} ref={yourRef} key={i}>{c.props.children}</c.type>
})