ReactJS 中的克隆元素

Clone Element in ReactJS

我想复制一个带有特定引用的元素,可以吗?

CODESANDBOX:https://codesandbox.io/s/new?file=/src/App.js:0-463

import "./styles.css";
import React, { useRef } from "react"

export default function App() {

  const elementRef = useRef();

  const clone = React.cloneElement( elementRef );

  return (
    <div className="App">
      <h1>Test React.cloneElement()</h1>
      <h2>I would duplicate this div:</h2>


      <div 
      className="div-style"
      ref= { elementRef }>
        div original
      </div>

<span> copy: </span>

 {/*{ clone } */}
 
    </div>
  );
}
import { useRef, useMemo, cloneElement } from "react";

export default function App() {
  const elementRef = useRef();

  const divElement = useMemo(() => {
    return <h2 ref={elementRef}>My element</h2>;
  }, [elementRef]);

  const clonedElement = useMemo(() => {
    return cloneElement(divElement);
  }, [divElement]);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      {divElement}
      {clonedElement}
    </div>
  );
}