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]);
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.
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.
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.
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:
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:
useImperativeHandle(ref, () => { // There is might be a difficult task console.log("useImperativeHandle calculated again"); return { focus: () => {} } }, []); // Array of dependencies is correct
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: .
useImperativeHandle(ref, () => { // ref is mutated directly ref.current = { customMethod: () => console.log("Error") }; });
Ndlela leyinene:
useImperativeHandle(ref, () => ({ customMethod: () => console.log("Correct"), }));
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: .
const increment = useCallback(() => { childRef.current.increment(); }, [])
Ndlela leyinene:
const increment = useCallback(() => { if (childRef.current?.increment) { childRef.current.increment() } }, [])
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: .
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:
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"); }, }), [] );
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:
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