createRef
createRef יוצרת אובייקט ref שיכול להכיל כל ערך.
class MyInput extends Component {
inputRef = createRef();
// ...
}Reference
createRef()
קראו ל-createRef כדי להצהיר על ref בתוך class component.
import { createRef, Component } from 'react';
class MyComponent extends Component {
intervalRef = createRef();
inputRef = createRef();
// ...Parameters
createRef לא מקבלת פרמטרים.
Returns
createRef מחזירה אובייקט עם מאפיין יחיד:
current: בתחילה מוגדר ל-null. לאחר מכן אפשר להגדיר אותו לערך אחר. אם מעבירים את אובייקט ה-ref ל-React כמאפייןrefל-JSX node, React תגדיר את המאפייןcurrentשלו.
Caveats
createRefתמיד מחזירה אובייקט שונה. זה שקול לכתיבה ידנית של{ current: null }.- בקומפוננטת פונקציה, כנראה שתרצו
useRef, שמחזירה תמיד את אותו אובייקט. const ref = useRef()שקול ל-const [ref, _] = useState(() => createRef(null)).
שימוש
הצהרה על ref בתוך class component
כדי להצהיר על ref בתוך class component, קראו ל-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> </> ); } }
חלופות
מעבר מ-class עם createRef לפונקציה עם useRef
אנחנו ממליצים להשתמש בקומפוננטות פונקציה במקום class components בקוד חדש. אם יש לכם class components קיימות שמשתמשות ב-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> </> ); }