Pitfall

createRef בשימוש בעיקר עבור class components. קומפוננטות פונקציה בדרך כלל נשענות על useRef במקום.

createRef יוצרת אובייקט ref יכול להכיל כל ערך.

class MyInput extends Component {
inputRef = createRef();
// ...
}

הפניה

createRef()

קראו ל-createRef כדי להצהיר על ref בתוך רכיב כיתה.

import { createRef, Component } from 'react';

class MyComponent extends Component {
intervalRef = createRef();
inputRef = createRef();
// ...

עוד דוגמאות נוספות.

פרמטרים

createRef לא מקבלת פרמטרים.

מחזירה

createRef מחזירה אובייקט עם מאפיין יחיד:

  • current: בתחילה מוגדרת ל-null. לאחר מכן אפשר להגדיר אותו לערך אחר. אם מעבירים את אובייקט ה-ref ל-React כמאפיין ref ל-JSX node, React תגדיר את המאפיין current שלו.

אזהרות

  • createRef תמיד מחזירה אובייקט שונה. זה שקול לכתיבה ידנית של { current: null }.
  • בקומפוננטת פונקציה, כנראה שתרצו useRef, שמחזירה תמיד את אותו אובייקט.
  • const ref = useRef() שקול ל-const [ref, _] = useState(() => createRef(null)).

שימוש

ההרהור על רכיב המחלקה

כדי להצהיר על ref בתוך רכיב כיתה, קראו ל-createRef והקצו את התוצאה לשדה במחלקה:

import { Component, createRef } from 'react';

class Form extends Component {
inputRef = createRef();

// ...
}

אם תעבירו עכשיו ref={this.inputRef} ל-<input> ב-JSX שלכם, React תאכלס את this.inputRef.current עם DOM node של שדה הקלט. לדוגמה, כך יוצרים כפתור שמפקס את השדה הקלט:

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}>
          Focus the input
        </button>
      </>
    );
  }
}

Pitfall

createRef בשימוש בעיקר עבור class components. קומפוננטות פונקציה בדרך כלל נשענות על useRef במקום.


חלופות

המשך מכיתה עם createRef לפונקציה עם useRef

אנחנו ממליצים להשתמש בקומפוננטות פונקציה במקום רכיבי כיתה בקוד חדש. אם יש לכם רכיבי כיתה קיימות שמשתמשות ב-createRef, כך אפשר להמיר אותן. זה הקוד המקורי:

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}>
          Focus the input
        </button>
      </>
    );
  }
}

כש-ממירים את הקומפוננטה הזו מ-class לפונקציה, מחליפים קריאות ל-createRef בקריאות ל-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}>
        Focus the input
      </button>
    </>
  );
}