paint-brush
Master React ka go Rala di-API tše di Atlegago Ka useImperativeHandle Hookka@socialdiscoverygroup
Histori e mpsha

Master React ka go Rala di-API tše di Atlegago Ka useImperativeHandle Hook

ka Social Discovery Group11m2024/12/23
Read on Terminal Reader

Nako e telele kudu; Go bala

Sekgoketšane sa useImperativeHandle ka go React se dumelela bahlami go ikgetha mekgwa le dithoto tšeo di pepentšhitšwego ke karolo, go godiša go fetofetoga le maemo le go hlokomelwa. E šoma le forwardRef go fana ka segokanyimmediamentsi sa sebolokigolo sa lenaneo bakeng sa dikarolo tša bana, go kgontšha taolo ya thwii godimo ga boitshwaro bja bona. Mekgwa ye mebotse e akaretša go arola tlhaologanyo ya ngwana, go nolofatša kopanyo le makgobapuku a motho wa boraro, le go efoga mereo ye e tlwaelegilego go swana le dihlopha tša go ithekga tše di fošagetšego. Ka go šomiša sekgoketšane se ka mo go atlegilego, bahlami ba ka hlama dikarolo tše di šomago gabotse kudu le go kaonafatša tshepedišo ya tirišo ka kakaretšo.
featured image - Master React ka go Rala di-API tše di Atlegago Ka useImperativeHandle Hook
Social Discovery Group HackerNoon profile picture
0-item
1-item

Ka tlhabollong ya sebjalebjale ya React, sekgoketšane sa useImperativeHandle ke tsela ye maatla ya go dira gore boleng bjo bo pepentšhitšwego bja karolo e be bja gago gomme e fa taolo ye ntši godimo ga mekgwa ya yona ya ka gare le dithoto. Ka lebaka leo, di-API tša Karolo tše di šomago gabotse kudu di ka kaonafatša go fetofetoga le maemo ga setšweletšwa le go hlokomelwa.


Ka sekotwana se, sehlopha sa Social Discovery Group ́s temogo itahlela ka mekgwa ye mekaone ya go šomiša useImperativeHandle ka mo go atlegilego go godiša dikarolo tša React.


React e fana ka digwegwe tše ntši (ditokomane tša semmušo di hlaloša digwegwe tše 17 go fihla ge go ngwalwa se) bakeng sa go laola mmušo, ditlamorago, le ditirišano magareng ga dikarolo.


Gare ga bona, useImperativeHandle ke sedirišwa se se nago le mohola sa go hlama segokanyimmediamentsi sa sebolokigolo sa lenaneo (API) sa dikarolo tša bana, seo se okeditšwego go React go tloga go phetolelo ya 16.8.0 go ya pele.


useImperativeHandle e go dumelela go ikgetha seo se tlago bušetšwa ke ref yeo e fetišitšwego go karolo. E šoma ka tandem le forwardRef, yeo e dumelelago ref go fetišetšwa go karolo ya ngwana.


 useImperativeHandle(ref, createHandle, [deps]);
  • ref - tshupiso fetisoa ho karolo.
  • createHandle - mošomo wo o bušetšago selo seo se tlago go fihlelelwa ka ref.
  • deps - le itšetlehileng hlophisitsoeng.


Sekgoketšane se se dumelela taolo ya ka ntle ya boitshwaro bja karolo, yeo e ka bago le mohola maemong a itšego, go swana le go šoma le makgobapuku a motho wa boraro, dipopaye tše di raraganego, goba dikarolo tšeo di nyakago phihlelelo ya thwii go mekgwa. Le ge go le bjalo, e swanetše go šomišwa ka kelohloko, ka ge e roba mokgwa wa go tsebagatša wa React.

Mohlala wa Motheo


A re naganeng re swanetše go laola DOM ya karolo ya ngwana. Mohlala wa ka moo o ka dirago se ka go šomiša ref.

 import React, { forwardRef, useRef } from 'react'; const CustomInput = forwardRef((props, ref) => { // Use forwardRef to pass the ref to the input element return <input ref={ref} {...props} />; }); export default function App() { const inputRef = useRef(); const handleFocus = () => { inputRef.current.focus(); // Directly controlling the input }; const handleClear = () => { inputRef.current.value = ''; // Directly controlling the input value }; return ( <div> <CustomInput ref={inputRef} /> <button onClick={handleFocus}>Focus</button> <button onClick={handleClear}>Clear</button> </div> ); }

Gomme mo ke ka fao e ka fihlelelwago ka go šomiša useImperativeHandle.

 import React, { useImperativeHandle, forwardRef, useRef } from 'react'; const CustomInput = forwardRef((props, ref) => { const inputRef = useRef(); useImperativeHandle(ref, () => ({ focus: () => { inputRef.current.focus(); }, clear: () => { inputRef.current.value = ''; }, })); return <input ref={inputRef} {...props} />; }); export default function App() { const inputRef = useRef(); return ( <div> <CustomInput ref={inputRef} /> <button onClick={inputRef.current.focus}>Focus</button> <button onClick={inputRef.current.clear}>Clear</button> </div> ); }


Bjalo ka ge go bonwe mehlaleng ye e lego ka mo godimo, ge o šomiša useImperativeHandle, karolo ya ngwana e fa motswadi sete ya mekgwa yeo re e hlalošago ka borena.


Mehola ya useImperativeHandle ge e bapetšwa le go fo šomiša ref


  1. E arola logiki ya karolo ya ngwana: E dumelela go fa dikarolo tša motswadi fela ka mekgwa ye e nyakegago.
  2. E nolofatša kopanyo: E dira gore go be bonolo go kopanya dikarolo tša React le makgobapuku ao a nyakago phihlelelo ya DOM ya thwii, go swana le Lottie goba Three.js.

Maemo a Tšwetšego Pele

Go šomiša useImperativeHandle maemong a maemo a godimo, go swana le mehlaleng ye e nago le dipopaye, go dumelela go arola boitshwaro bjo bo raraganego ka gare ga karolo. Se se dira gore karolo ya motswadi e be bonolo le go balwa kudu, kudu ge o šoma ka dilaeborari tša dipopaye goba tša modumo.



 import React, { useRef, useState, useImperativeHandle, forwardRef, memo } from "react"; import { Player } from '@lottiefiles/react-lottie-player' import animation from "./animation.json"; const AnimationWithSound = memo( forwardRef((props, ref) => { const [isAnimating, setIsAnimating] = useState(false); const animationRef = useRef(null); const targetDivRef = useRef(null); useImperativeHandle( ref, () => ({ startAnimation: () => { setIsAnimating(true); animationRef.current?.play() updateStyles("start"); }, stopAnimation: () => { animationRef.current?.stop() updateStyles("stop"); }, }), [] ); const updateStyles = (action) => { if (typeof window === 'undefined' || !targetDivRef.current) return; if (action === "start") { if (targetDivRef.current.classList.contains(styles.stop)) { targetDivRef.current.classList.remove(styles.stop); } targetDivRef.current.classList.add(styles.start); } else if (action === "stop") { if (targetDivRef.current.classList.contains(styles.start)) { targetDivRef.current.classList.remove(styles.start); } targetDivRef.current.classList.add(styles.stop); } }; return ( <div> <Player src={animation} loop={isAnimating} autoplay={false} style={{width: 200, height: 200}} ref={animationRef} /> <div ref={targetDivRef} className="target-div"> This div changes styles </div> </div> ); }) ); export default function App() { const animationRef = useRef(); const handleStart = () => { animationRef.current.startAnimation(); }; const handleStop = () => { animationRef.current.stopAnimation(); }; return ( <div> <h1>Lottie Animation with Sound</h1> <AnimationWithSound ref={animationRef} /> <button onClick={handleStart}>Start Animation</button> <button onClick={handleStop}>Stop Animation</button> </div> ); }


Mohlaleng wo, karolo ya ngwana e bušetša mekgwa ya startAnimation le stopAnimation, yeo e akaretšago logic ye e raraganego ka gare ga yona.


Diphošo tše di Tlwaelegilego le Merao

1. Ka mo go fošagetšego tlala go ithekga lenaneo

Phošo ga se ka mehla e lemogegago gatee-tee. Ka mohlala, karolo ya motswadi e ka fetoša didirišwa tša go thekga gantši, gomme o ka kopana le seemo seo go sona mokgwa wo o fetilwego ke nako (wo o nago le datha ye e senyegilego) o tšwelago pele go šomišwa.


Phošo ya mohlala:

https://sebedisa-taelo-tshwara.levkovich.dev / deps-ha-ne-nepahe / phoso

 const [count, setCount] = useState(0); const increment = useCallback(() => { console.log("Current count in increment:", count); // Shows old value setCount(count + 1); // Are using the old value of count }, [count]); useImperativeHandle( ref, () => ({ increment, // Link to the old function is used }), [] // Array of dependencies do not include increment function );


Mokgwa o nepagetšego:

https://sebedisa-taelo-tshwaro.levkovich.dev / deps-ha se-nepahetse / nepahetseng

 const [count, setCount] = useState(0); useImperativeHandle( ref, () => ({ increment, }), [increment] // Array of dependencies include increment function );


2. Go hloka go ithekga ga lenaneo


Ge e le gore lenaneo la go ithekga ga le fiwe, React e tla tšea gore selo seo se šomišwagoImperativeHandle se swanetše go hlolwa gape go render ye nngwe le ye nngwe. Se se ka hlola ditaba tše bohlokwa tša tshepedišo, kudu ge e le gore dipalopalo tše "boima" di dirwa ka gare ga sekgoketšane.


Phošo ya mohlala:

 useImperativeHandle(ref, () => { // There is might be a difficult task console.log("useImperativeHandle calculated again"); return { focus: () => {} } }); // Array of dependencies is missing


Mokgwa o nepagetšego:

https://sebedisa-taelo-tshwara.levkovich.dev / deps-lefeela / nepahetseng

 useImperativeHandle(ref, () => { // There is might be a difficult task console.log("useImperativeHandle calculated again"); return { focus: () => {} } }, []); // Array of dependencies is correct


  1. Go fetola ref ka gare ga useImperativeHandle

Phetošo ya thwii ya ref.current e šitiša boitshwaro bja React. Ge React e leka go mpshafatša ref, e ka lebiša go dithulano goba diphošo tše di sa letelwago.


Phošo ya mohlala:

https://sebedisa-taelo-tshwara.levkovich.dev / ref-phetolo / phoso


 useImperativeHandle(ref, () => { // ref is mutated directly ref.current = { customMethod: () => console.log("Error") }; });

Mokgwa o nepagetšego:

https://sebedisa-taelo-tshwara.levkovich.dev / ref-phetolo / nepahetseng


 useImperativeHandle(ref, () => ({ customMethod: () => console.log("Correct"), }));


  1. Go šomiša mekgwa pele e thongwa


Mekgwa ya go bitša yeo e filwego ka useImperativeHandle go tšwa go useEffect goba bašomiši ba ditiragalo, go tšea gore ref e šetše e le gona, e ka lebiša go diphošo — ka mehla hlahloba bjale pele o bitša mekgwa ya yona.


Phošo ya mohlala:


https://sebedisa-setshwaro-se-taelo.levkovich.dev/pele-init/phoso

 const increment = useCallback(() => { childRef.current.increment(); }, [])


Mokgwa o nepagetšego:

https://sebedisa-taelo-tshwara.levkovich.dev / pele-init / nepahetseng


 const increment = useCallback(() => { if (childRef.current?.increment) { childRef.current.increment() } }, [])


  1. Ditaba tša go nyalantšha magareng ga ditshwantšho tša dipopaye le mmušo

Ge e le gore useImperativeHandle e bušetša mekgwa yeo e fetošago seemo ka go sepelelana (mohlala, go thoma animation le go fetoša ditaele ka nako e tee), e ka hlola "sekgoba" magareng ga seemo sa pono le logiki ya ka gare. Netefatša go se fetoge magareng ga boitshwaro le boitshwaro bja pono, mohlala, ka go šomiša ditlamorago (useEffect).


Phošo ya mohlala:

https://sebedisa-taelo-tshwara.levkovich.dev / mmuso-animation-sync / phoso


 useImperativeHandle(ref, () => ({ startAnimation: () => { setState("running"); // Animation starts before the state changes lottieRef.current.play(); }, stopAnimation: () => { setState("stopped"); // Animation stops before the state changes lottieRef.current.stop(); }, }));


Mokgwa o nepagetšego:


https://sebedisa-taelo-tshwara.levkovich.dev / mmuso-animation-sync / nepahetseng

 useEffect(() => { if (state === "running" && lottieRef.current) { lottieRef.current.play(); } else if (state === "stopped" && lottieRef.current) { lottieRef.current.stop(); } }, [state]); // Triggered when the state changes useImperativeHandle( ref, () => ({ startAnimation: () => { setState("running"); }, stopAnimation: () => { setState("stopped"); }, }), [] );

Mafetšo

Go šomiša useImperativeHandle go lokafaditšwe maemong a a latelago:


  • Go laola boitshwaro bja karolo ya ngwana: Go fa mohlala, go fa mokgwa wa go tsepelela goba wa go seta gape bakeng sa karolo ya tsenyo ye e raraganego.

  • Go uta dintlha tša phethagatšo: Karolo ya motswadi e amogela fela mekgwa yeo e e hlokago, e sego selo ka moka sa ref.


Pele o šomiša useImperativeHandle, ipotšiše dipotšišo tše:

  • Na mošomo o ka rarollwa ka go tsebagatša go dirišwa mmušo, didirišwa tša go thekga goba taba yeo e dikologilego? Ge e ba ee, yeo ke mokgwa wo o kgethwago.
  • Ge e le gore ga go bjalo, gomme karolo e swanetše go fa segokanyimmediamentsi sa sebolokigolo sa ka ntle, šomiša useImperativeHandle.


Ka go tseba sekgoketšane sa useImperativeHandle gabotse, bahlami ba React ba ka hlama dikarolo tše di šomago gabotse kudu le tše di hlokomelwago ka go pepentšha mekgwa ka go kgetha. Dithekniki tšeo di beakantšwego ke sehlopha sa Sehlopha sa Kutollo ya Leago di ka thuša bahlami go kaonafatša go fetofetoga ga bona, go nolofatša di-API tša bona tša dikarolo, le go godiša tshepedišo ya tirišo ka kakaretšo.


E ngwadilwe ke Sergey Levkovich, Moentšeneare yo Mogolo wa Software go Sehlopha sa Kutollo ya Leago


L O A D I N G
. . . comments & more!

About Author

Social Discovery Group HackerNoon profile picture
Social Discovery Group@socialdiscoverygroup
We solve the problem of loneliness, isolation, and disconnection with the help of digital reality.

HANG TAGS YA GO FEGA

ARTICLE YE E HLAHILWE KA...