createRef
createRef crea un oggetto ref che può contenere un valore arbitrario.
class MyInput extends Component {
inputRef = createRef();
// ...
}Reference
createRef()
Chiama createRef per dichiarare una ref all’interno di un componente classe.
import { createRef, Component } from 'react';
class MyComponent extends Component {
intervalRef = createRef();
inputRef = createRef();
// ...Parameters
createRef non accetta parametri.
Returns
createRef restituisce un oggetto con una singola proprietà:
current: inizialmente è impostato sunull. Puoi cambiarlo in seguito con un altro valore. Se passi l’oggetto ref a React come attributorefsu un nodo JSX, React imposterà la sua proprietàcurrent.
Caveats
createRefrestituisce sempre un oggetto diverso. Equivale a scrivere{ current: null }manualmente.- In un componente funzione, probabilmente preferirai
useRef, che restituisce sempre lo stesso oggetto. const ref = useRef()equivale aconst [ref, _] = useState(() => createRef(null)).
Usage
Dichiarare una ref in un componente classe
Per dichiarare una ref all’interno di un componente classe, chiama createRef e assegna il risultato a un campo di classe:
import { Component, createRef } from 'react';
class Form extends Component {
inputRef = createRef();
// ...
}Se passi ref={this.inputRef} a un <input> nel tuo JSX, React popolerà this.inputRef.current con il nodo DOM dell’input. Ad esempio, ecco come creare un pulsante che mette a fuoco l’input:
import { Component, createRef } from 'react'; export default class Form extends Component { inputRef = createRef(); handleClick = () => { this.inputRef.current.focus(); } render() { return ( <> <input ref={this.inputRef} /> <button onClick={this.handleClick}> Metti a fuoco l'input </button> </> ); } }
Alternatives
Migrare da una classe con createRef a una funzione con useRef
Nel codice nuovo consigliamo di usare componenti funzione al posto dei componenti classe. Se hai componenti classe esistenti che usano createRef, ecco come convertirli. Questo è il codice originale:
import { Component, createRef } from 'react'; export default class Form extends Component { inputRef = createRef(); handleClick = () => { this.inputRef.current.focus(); } render() { return ( <> <input ref={this.inputRef} /> <button onClick={this.handleClick}> Metti a fuoco l'input </button> </> ); } }
Quando converti questo componente da classe a funzione, sostituisci le chiamate a createRef con chiamate a useRef:
import { useRef } from 'react'; export default function Form() { const inputRef = useRef(null); function handleClick() { inputRef.current.focus(); } return ( <> <input ref={inputRef} /> <button onClick={handleClick}> Metti a fuoco l'input </button> </> ); }