कस्टम कॉम्पोनेंटला पास केलेला ref त्याच्या आत असलेल्या DOM नोडला स्वयंचलितपणे पोहोचत नाही. forwardRef कॉम्पोनेंटला प्राप्त करून त्याला चाइल्ड एलिमेंटला संलग्न करू देते. कस्टमाइज करते ते उघड करते.
कस्टम कॉम्पोनेंटला पास केलेला ref त्याच्या आत असलेल्या DOM नोडला स्वयंचलितपणे पोहोचत नाही. forwardRef कॉम्पोनेंटला प्राप्त करून त्याला चाइल्ड एलिमेंटला संलग्न करू देते. कस्टमाइज करते ते उघड करते.
refuseImperativeHandlerefconst 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();
कधीकधी आपण संपूर्ण DOM नोड लीक करू इच्छित नाही — केवळ विशिष्ट पद्धतीः
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();
संप्रेषणासाठी props/state पसंत करा. केवळ खरोखर अनिवार्य गरजांसाठी refs वापरा: फोकस व्यवस्थापन, स्क्रोलिंग, मजकूर निवड, मीडिया प्लेबॅक, किंवा अनिवार्य लायब्रेरीचे एकीकरण. नोट: React 19 मध्ये, ref सामान्य prop म्हणून पास केले जाऊ शकते, म्हणून forwardRef अनेकदा यापुढे आवश्यक नाही.
सविस्तर उत्तरांसह IT मुलाखत प्रश्नांचे ग्रंथालय — Junior पासून Senior पर्यंत.
देणगी द्या