paint-brush
Master React hi ku Dizayina Ti-API leti Humelelaka Hi useImperativeHandle Hookhi@socialdiscoverygroup
Matimu lamantshwa

Master React hi ku Dizayina Ti-API leti Humelelaka Hi useImperativeHandle Hook

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

Ku leha ngopfu; Ku hlaya

Xihuku xa useImperativeHandle eka React xi pfumelela vatumbuluxi ku lulamisa tindlela na swihlawulekisi leswi paluxiweke hi xiphemu, ku ndlandlamuxa ku cincacinca na ku hlayisiwa. Yi tirha na forwardRef ku nyika xihlanganisi xa phurogireme xa swiphemu swa n’wana, ku endla leswaku ku va na vulawuri byo kongoma eka mahanyelo ya swona. Maendlelo lamanene ya katsa ku hambanyisa logic ya n’wana, ku olovisa ku hlanganisiwa na tilayiburari ta vanhu va vunharhu, na ku papalata mintlhamu leyi tolovelekeke ku fana na ti array ta ku titshega leti hoxeke. Hi ku tirhisa xihuku lexi hi ndlela leyinene, vaendli va nga tumbuluxa swiphemu leswi tirhaka kahle no antswisa matirhelo ya app hi ku angarhela.
featured image - Master React hi ku Dizayina Ti-API leti Humelelaka Hi useImperativeHandle Hook
Social Discovery Group HackerNoon profile picture
0-item
1-item

Eka nhluvukiso wa manguva lawa wa React, useImperativeHandle hook i ndlela ya matimba yo endla leswaku xiphemu lexi nga erivaleni xa nkoka naswona xi nyika vulawuri byo tala eka tindlela ta xona ta le ndzeni na swihlawulekisi. Hikwalaho ka sweswo, ti-API ta Xiphemu leti tirhaka kahle swinene ti nga antswisa ku cinca-cinca ka xiendliwa na ku hlayisiwa.


Eka xiphemu lexi, vutivi bya ntlawa wa Social Discovery Group ́s byi nghena eka maendlelo lamanene yo tirhisa useImperativeHandle hi ndlela leyinene ku ndlandlamuxa swiphemu swa React.


React yi nyika ti hook to tala (matsalwa ya ximfumo ya hlamusela 17 wa ti hook ku fikela loko hi tsala xiviko lexi) ku lawula xiyimo, vuyelo, na ku tirhisana exikarhi ka swiphemu.


Exikarhi ka swona, useImperativeHandle i xitirhisiwa lexi pfunaka xo tumbuluxa xihlanganisi xa phurogireme (API) xa swiphemu swa n’wana, lexi engeteriweke eka React ku sukela eka vuhundzuluxeri bya 16.8.0 ku ya emahlweni.


useImperativeHandle yi ku pfumelela ku lulamisa leswi nga ta vuyiseriwa hi ref leyi hundziseriweke eka xiphemu. Yi tirha hi ku fambisana na forwardRef, leyi pfumelelaka ku hundziseriwa ref eka xiphemu xa n’wana.


 useImperativeHandle(ref, createHandle, [deps]);
  • ref — xikombo lexi hundziseriweke eka xiphemu.
  • createHandle — ntirho lowu vuyisaka nchumu lowu nga ta fikeleleka hi ku tirhisa ref.
  • deps — xirhendzevutani xa ku titshega.


Xihuku lexi xi pfumelela vulawuri bya le handle bya mahanyelo ya xiphemu, leswi nga pfunaka eka swiyimo swo karhi, swo tanihi ku tirha na tilayiburari ta vanhu va vunharhu, swifaniso leswi hanyaka leswi rharhanganeke, kumbe swiphemu leswi lavaka ku fikelela hi ku kongoma eka tindlela. Kambe yi fanele ku tirhisiwa hi vukheta, tanihileswi yi tshovaka endlelo ra xitiviso ra React.

Xikombiso xa Xisekelo


A hi ehleketeni leswaku hi fanele ku manipulate DOM ya xiphemu xa n’wana. Hi lexi xikombiso xa ndlela yo endla leswi hi ku tirhisa 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> ); }

Naswona hi leyi ndlela leyi swi nga fikeleriwa ha yona hi ku tirhisa 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> ); }


Hilaha swi voniweke hakona eka swikombiso leswi nga laha henhla, loko hi tirhisa useImperativeHandle, xiphemu xa n’wana xi nyika mutswari sete ya tindlela leti hi ti hlamuselaka hi hexe.


Swipfuno swa useImperativeHandle loko swi pimanisiwa na ku tirhisa ntsena ref


  1. Yi hambanyisa loji ya xiphemu xa n’wana: Yi pfumelela ku nyika swiphemu swa mutswari ntsena hi tindlela leti lavekaka.
  2. Ku olovisa ku hlanganisiwa: Swi olovisa ku hlanganisa swiphemu swa React na tilayiburari leti lavaka mfikelelo wo kongoma wa DOM, ku fana na Lottie kumbe Three.js.

Swiendlakalo swa le Henhla

Ku tirhisa useImperativeHandle eka swiyimo swa le henhla, ku fana na le ka swikombiso leswi nga na swifaniso leswi hanyaka, swi pfumelela ku hambanyisa mahanyelo yo rharhangana endzeni ka xiphemu. Leswi swi endla leswaku xiphemu xa mutswari xi olova no hlayeka, ngopfungopfu loko u tirha na tilayiburari ta swifaniso leswi hanyaka kumbe swa mpfumawulo.



 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> ); }


Eka xikombiso lexi, xiphemu xa n’wana xi vuyisa tindlela ta startAnimation na stopAnimation, leti hlanganisaka logic yo rharhangana endzeni ka tona.


Swihoxo Leswi Tolovelekeke Ni Mintlhamu

1. Xirhendzevutani xa ku titshega lexi tatiweke hi ndlela leyi hoxeke

Xihoxo a hi minkarhi hinkwayo xi vonakaka hi ku hatlisa. Xikombiso, xiphemu xa mutswari xi nga ha tshamela ku cinca switirhisiwa, naswona u nga ha hlangana na xiyimo laha ndlela leyi hundzeriweke hi nkarhi (leyi nga na datha leyi nga tirhiki) yi yaka emahlweni yi tirhisiwa.


Xikombiso xa xihoxo: .

https://tirhisa-xileriso-xikhomela-xileriso.levkovich.dev/deps-a-yi-nga-ri kahle/xi hoxile

 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 );


Ndlela leyinene:

https://tirhisa-xileriso-xikhomela.levkovich.dev/deps-a-yi-lulami/yi lulamile

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


2. Ku kayivela ka ku titshega ka array


Loko array ya ku titshega yi nga nyikiwanga, React yi ta teka leswaku nchumu lowu nga eka useImperativeHandle wu fanele ku tumbuluxiwa nakambe eka render yin’wana na yin’wana. Leswi swi nga vanga timhaka ta nkoka ta matirhelo, ngopfungopfu loko swibalo swa "ku tika" swi endliwa endzeni ka xihuku.


Xikombiso xa xihoxo: .

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


Ndlela leyinene:

https://tirhisa-xileriso-xikhomela.levkovich.dev/deps-empty/correct

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


  1. Ku cinca ref endzeni ka useImperativeHandle

Ku cinciwa hi ku kongoma ka ref.current swi kavanyeta mahanyelo ya React. Loko React yi ringeta ku pfuxeta ref, swi nga vanga ku kanetana kumbe swihoxo leswi nga languteriwangiki.


Xikombiso xa xihoxo: .

https://tirhisa-xileriso-xikhomela.levkovich.dev/ref-ku cinca/swi hoxile


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

Ndlela leyinene:

https://tirhisa-xileriso-xikhomela.levkovich.dev/ref-ku cinca/swi lulamile


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


  1. Ku tirhisa tindlela ti nga si sunguriwa


Maendlelo yo vitana lama nyikiweke hi ku tirhisa useImperativeHandle ku suka eka useEffect kumbe vafambisi va swiendlakalo, hi ku ehleketa leswaku ref se ya kumeka, swi nga vanga swihoxo — minkarhi hinkwayo kambela sweswi u nga si vitana tindlela ta yona.


Xikombiso xa xihoxo: .


https://tirhisa-xileriso-xikhomela.levkovich.dev/before-init/wrong

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


Ndlela leyinene:

https://tirhisa-xileriso-xikhomela.levkovich.dev/before-init/swi lulamile


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


  1. Timhaka ta ku fambisana exikarhi ka swifaniso leswi hanyaka na xiyimo

Loko useImperativeHandle yi vuyisa tindlela leti cincaka xiyimo hi ku fambisana (xikombiso, ku sungula animation na ku cinca switayele hi nkarhi wun'we), swi nga vanga "xivandla" exikarhi ka xiyimo xa xivono na loji ya le ndzeni. Tiyisisa ku ringanana exikarhi ka xiyimo na mahanyelo ya swivono, xikombiso, hi ku tirhisa switandzhaku (useEffect).


Xikombiso xa xihoxo: .

https://tirhisa-xileriso-xikhomela.levkovich.dev/xiyimo-xifaniso-xifaniso/xi hoxile


 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(); }, }));


Ndlela leyinene:


https://tirhisa-xileriso-xikhomela.levkovich.dev/xiyimo-xifaniso-xifaniso/xi lulamile

 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"); }, }), [] );

Mahetelelo

Ku tirhisa useImperativeHandle swi lulamile eka swiyimo leswi landzelaka:


  • Ku lawula mahanyelo ya xiphemu xa n’wana: Xikombiso, ku nyika ndlela yo kongomisa kumbe ku tlherisela eka xiphemu xa ku nghenisa lexi rharhanganeke.

  • Ku fihla vuxokoxoko bya ku tirhisiwa: Xiphemu xa mutswari xi amukela ntsena tindlela leti xi ti lavaka, ku nga ri nchumu hinkwawo wa ref.


Loko u nga si tirhisa useImperativeHandle, tivutise swivutiso leswi:

  • Xana ntirho wu nga tlhantlhiwa hi ndlela yo tivisa hi ku tirhisa xiyimo, switirhisiwa swo pfuneta kumbe mongo? Loko ku ri ina, yoleyo i ndlela leyi rhandzekaka.
  • Loko swi nga ri tano, naswona xiphemu xi lava ku nyika xihlanganisi xa le handle, tirhisa useImperativeHandle.


Hi ku va na vutshila eka useImperativeHandle hook, vaendli va React va nga tumbuluxa swiphemu leswi tirhaka kahle no hlayisiwa hi ku hlawula tindlela to paluxa. Tithekiniki leti vekiweke hi ntlawa wa Ntlawa wa Social Discovery ti nga pfuna vaendli ku antswisa ku cinca-cinca ka vona, ku olovisa ti-API ta vona ta swiphemu, na ku ndlandlamuxa matirhelo ya app hi ku angarhela.


Yi tsariwe hi Sergey Levkovich, Muinjhiniyere wa Software wa le Henhla eka Social Discovery Group


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

XITLHOKOVETSELO LEXI XI NYIKERIWE EKA...