Code Example 1: Creating ref
❓ В чём разница между useRef и createRef? Когда какой использовать?
Functional component:
import { useRef } from 'react';
function MyComponent() {
const inputRef = useRef<HTMLInputElement>(null);
return <input ref={inputRef} />;
}
Class component:
import { Component, createRef } from 'react';
class MyComponent extends Component {
inputRef = createRef<HTMLInputElement>();
render() {
return <input ref={this.inputRef} />;
}
}
Code Example 2: Focus management
❓ Что делает passwordRef.current?.focus()? Когда ref.current становится доступным?
import { useRef } from 'react';
function LoginForm() {
const emailRef = useRef<HTMLInputElement>(null);
const passwordRef = useRef<HTMLInputElement>(null);
const handleEmailSubmit = () => {
passwordRef.current?.focus();
};
return (
<form>
<input
ref={emailRef}
type="email"
placeholder="Email"
onKeyDown={(e) => e.key === 'Enter' && handleEmailSubmit()}
/>
<input
ref={passwordRef}
type="password"
placeholder="Пароль"
/>
</form>
);
}
Code Example 3: Storing previous value
❓ Почему для хранения предыдущего значения используется ref, а не state? Что происходит при изменении ref.current?
import { useRef, useEffect, useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const prevCountRef = useRef<number>(0);
useEffect(() => {
prevCountRef.current = count;
});
return (
<div>
<p>Текущее: {count}</p>
<p>Предыдущее: {prevCountRef.current}</p>
<button onClick={() => setCount(c => c + 1)}>+1</button>
</div>
);
}
Code Example 4: Third-party library integration
❓ Зачем здесь нужны два ref? Как происходит интеграция с внешней библиотекой?
import { useRef, useEffect } from 'react';
import Chart from 'chart.js';
function ChartComponent({ data }) {
const canvasRef = useRef<HTMLCanvasElement>(null);
const chartRef = useRef<Chart | null>(null);
useEffect(() => {
if (canvasRef.current) {
chartRef.current = new Chart(canvasRef.current, {
type: 'line',
data: data
});
}
return () => {
chartRef.current?.destroy();
};
}, [data]);
return <canvas ref={canvasRef} />;
}
Code Example 5: forwardRef
❓ Почему Version A не работает? Что делает forwardRef?
Version A:
function MyInput(props) {
return <input {...props} />;
}
Version B:
const MyInput = forwardRef<HTMLInputElement, Props>((props, ref) => {
return <input ref={ref} {...props} />;
});
function Parent() {
const inputRef = useRef<HTMLInputElement>(null);
return <MyInput ref={inputRef} />;
}
Code Example 6: Callback ref
❓ Чем callback ref отличается от объекта ref? Когда вызывается эта функция?
function MeasureExample() {
const measureRef = (node: HTMLDivElement | null) => {
if (node !== null) {
console.log('Размеры:', node.getBoundingClientRect());
}
};
return <div ref={measureRef}>Измеряемый элемент</div>;
}