reactjs / reactjs/react.dev

[Docs] React.cloneElement and forwarding ref

Aperta
#2,337 1 commento 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Lingua principale
JavaScript
Stelle
11.8k
Fork
7.9k
Merge medio
1g 11h
PR unite (30g)
11

Descrizione

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?

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Esamina la sezione dell’API React cloneElement collegata nell’issue e confronta la formulazione relativa a ref con l’esempio ChangeTitle fornito. Chiarisci quale ref viene mantenuto e come React.forwardRef può passare un ref; il lavoro è completo quando la spiegazione descrive accuratamente l’avviso e l’utilizzo corretto.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
react
Ambito
documentation
Tipo di issue
Documentazione
Difficoltà
2/5
Tempo stimato
1-3 ore
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
48/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.