【问题标题】:How to add react reference to HTMLCollection items?如何添加对 HTMLCollection 项目的反应引用?
【发布时间】:2021-03-05 19:24:02
【问题描述】:

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

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

【问题讨论】:

    标签: reactjs react-markdown


    【解决方案1】:

    您可以使用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>
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-18
      • 2012-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-25
      • 2010-09-11
      相关资源
      最近更新 更多