ref wanda aka damje zuwa custom component ba ya isa ga DOM node a cikinta kai tsaye ba. forwardRef yana ba da damar component na karba ref da kuma makala shi ga element na yara. useImperativeHandle yana daidaita abin da ref ya baje.
ref wanda aka damje zuwa custom component ba ya isa ga DOM node a cikinta kai tsaye ba. forwardRef yana ba da damar component na karba ref da kuma makala shi ga element na yara. useImperativeHandle yana daidaita abin da ref ya baje.
const TextInput = forwardRef(function TextInput(props, ref) {
return <input ref={ref} {...props} />; // parent's ref now points to the <input>
});
// parent can focus the inner input:
const ref = useRef(null);
<TextInput ref={ref} />;
// ref.current.focus();
Wani lokaci ba kwa so ka fallashi DOM node duka — kawai takawar hanyoyi:
const FancyInput = forwardRef(function FancyInput(props, ref) {
const inner = useRef(null);
useImperativeHandle(ref, () => ({
focus: () => inner.current.focus(),
clear: () => { inner.current.value = ""; },
}), []);
return <input ref={inner} {...props} />;
});
// parent: fancyRef.current.focus(); fancyRef.current.clear();
Gi prioritize props/state don sadarwa. Ku nufi refs kawai don gaske imperative bukatu: focus management, scrolling, text selection, media playback, ko haɗa libraries na imperative. Lura: a cikin React 19, ref zai iya damjewa azaman regular prop, don haka forwardRef sai da yake ba shakara ba.
Ɗakin karatu na tambayoyin hira na IT tare da amsoshi cikakke — daga Junior zuwa Senior.
Ba da Gudummawa