reactjs / reactjs/react.dev

[Docs] React.cloneElement and forwarding ref

Offen
#2,337 1 Kommentar 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

Vorherrschende Sprache
JavaScript
Sterne
11.8k
Forks
7.9k
Ø Merge
1 T. 11 Std.
Gemergte PRs (30 T.)
11

Beschreibung

Hi, I believe the documentation about React.cloneElement is not very clear about handling refs.

I am talking about that part: https://reactjs.org/docs/react-api.html#cloneelement

However, it also preserves refs. This means that if you get a child with a ref on it, you won’t accidentally steal it from your ancestor. You will get the same ref attached to your new element.

Now, let's see consider the following use case (simplified):

const ChangeTitle = ({ children, ...otherProps }) =>
  React.cloneElement(children, { 
    ...otherProps, 
    title: 'Title was changed'
  })

function MyComponent() {
  const myRef = React.useRef()
  return (
    <ChangeTitle ref={myRef}>
      <span>This is my component</span>
    </ChangeTitle>
  )
}

This throws a console warning about ChangeTitle unable to hold a ref.

In my original understanding of the docs, I though ChangeTitle would become the cloned element, which, as the docs explains, retain it's original ref, hance the one given by Mycomponent.

Instead, this is obviously wrong, and the cloned element would only retain a ref if it was given to itself, not the parent component, hence something like <span ref={spanRef}>This is my component</span>.

I guess the fix to the above code is the following:

const ChangeTitle = React.forwardRef(({ children, ...otherProps }, ref) =>
  React.cloneElement(children, { 
    ...otherProps, 
    ref,
    title: 'Title was changed'
  }))

Correct?

Is it worth adding specifically that cloneElement can contain the ref prop if used with React.forwardRef in a functional component?

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Überprüfe den im Issue verlinkten Abschnitt zur React API cloneElement und vergleiche die Formulierung zu ref mit dem bereitgestellten ChangeTitle-Beispiel. Kläre, welcher ref beibehalten wird und wie React.forwardRef einen ref durchreichen kann; abgeschlossen ist die Aufgabe, wenn die Erklärung die Warnung und die korrigierte Verwendung准确 beschreibt.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
react
Bereich
documentation
Issue-Typ
Dokumentation
Schwierigkeit
2/5
Geschätzter Aufwand
1-3 Stunden
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
48/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.