कस्टम कम्पोनेन्टलाई पास गरिएको ref यसको भित्रको DOM नोडमा स्वचालित रूपमा पुग्दैन। forwardRef कम्पोनेन्टलाई ref प्राप्त गरी यसलाई बाल एलिमेन्टमा संलग्न गर्न देय। useImperativeHandle ती ref ले के प्रदर्शन गर्छ भनेर कस्टमाइज गर्छ।
कस्टम कम्पोनेन्टलाई पास गरिएको ref यसको भित्रको DOM नोडमा स्वचालित रूपमा पुग्दैन। forwardRef कम्पोनेन्टलाई ref प्राप्त गरी यसलाई बाल एलिमेन्टमा संलग्न गर्न देय। useImperativeHandle ती ref ले के प्रदर्शन गर्छ भनेर कस्टमाइज गर्छ।
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();
कहिले काहीँ तपाईँ पूरै 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 प्राय: अब आवश्यक छैन।