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