亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
Understand the combined application of React Context and Ref
Limitations of blur events and advantages of focusout
Use the focusout event to implement correct out-of-focus monitoring
Summarize
Home Web Front-end JS Tutorial A practical guide to managing Ref and handling focus events through Context in React

A practical guide to managing Ref and handling focus events through Context in React

Oct 15, 2025 am 11:21 AM

A practical guide to managing Ref and handling focus events through Context in React

This article explores how to correctly handle focus events in React applications when passing the ref of a DOM element to a child component through the Context. In response to the problem that the blur event does not bubble up, resulting in the inability to capture the out-of-focus child elements on the parent element, the article proposes using the focusout event as a solution, and provides detailed code examples and explanations to ensure the correct setting and cleanup of event listeners.

Understand the combined application of React Context and Ref

In React, ref is a way to access a DOM node or component instance. When we need to share the ref of a DOM element between multiple components, React Context provides an efficient and concise mechanism. For example, a parent component may have a ref of a DOM element and want its child components to perform certain operations based on this ref, such as adding event listeners.

Consider the following scenario: an EditorProvider component manages the ref of a div element and exposes it to consuming components through Context.

 import React, { useRef, useContext, useMemo } from 'react';

// Define the type of Context interface EditorContextProps {
    historyState: any; // Example, the specific type is defined according to actual needs ref: React.RefObject<htmldivelement>;
}

// Create Context
const EditorContext = React.createContext<editorcontextprops undefined>(undefined);

// Customize Hook to facilitate context consumption
export function useEditorContext(): EditorContextProps {
    const context = useContext(EditorContext);
    if (context === undefined) {
        throw new Error('useEditorContext must be used within an EditorProvider');
    }
    return context;
}

// EditorProvider component export default function EditorProvider({ children }: { children: React.ReactNode }) {
    const ref = useRef<htmldivelement>(null); // Create ref
    const historyState = useMemo(() => ({ /* Initial state */ }), []); // Example const context = { historyState, ref };

    return (
        <editorcontext.provider value="{context}">
            <div ref="{ref}"> {/* Bind ref to DOM element*/}
                {children}
            </div>
        </editorcontext.provider>
    );
}</htmldivelement></editorcontextprops></htmldivelement>

The above code shows how to share the ref of an HTMLDivElement through EditorProvider. The consuming component (such as a Lexical plug-in) can obtain this ref through the useEditorContext hook.

Limitations of blur events and advantages of focusout

When consuming components try to listen for out-of-focus events on this shared ref, a common misunderstanding is to use the blur event.

 import React, { useEffect, useCallback } from 'react';
import { useEditorContext } from './EditorProvider'; // Assume path function MyLexicalPlugin() {
    const { ref } = useEditorContext();

    const blurHandler = useCallback((event: FocusEvent) => {
        console.log('Blurred');
        // Handle defocus logic here}, []);

    useEffect(() => {
        const element = ref.current;
        if (element) {
            // Error demonstration: blur event does not bubble element.addEventListener('blur', blurHandler, false);
        }

        return () => {
            if (element) {
                element.removeEventListener('blur', blurHandler);
            }
        };
    }, [ref.current, blurHandler]); // Dependencies include ref.current

    return null; // Plugins usually do not render the DOM
}

In the above code, blurHandler may not trigger as expected, especially when the focus moves away from a child element inside the div pointed to by the ref. This is because blur events don't bubble up . This means that if focus moves away from a child element, the blur event will only be triggered on that child element and will not be propagated to its parent element (i.e. the div we referenced via ref).

To solve this problem we should use focusout event . The focusout event is similar to the blur event, both indicating that the element has lost focus, but the key difference is that the focusout event bubbles up . The focusout event is triggered on an element when the element itself or any of its descendants loses focus. This makes it ideal for monitoring child element out-of-focus behavior on a parent element.

Use the focusout event to implement correct out-of-focus monitoring

Replace the blur event in useEffect with focusout to solve the problem:

 import React, { useEffect, useCallback } from 'react';
import { useEditorContext } from './EditorProvider'; // Assume path function MyLexicalPlugin() {
    const { ref } = useEditorContext();

    const blurHandler = useCallback((event: FocusEvent) => {
        console.log('Blurred or focus moved out from a child element');
        // Handle defocus logic here}, []);

    useEffect(() => {
        const element = ref.current;
        if (element) {
            // Correct approach: use focusout event, it will bubble element.addEventListener('focusout', blurHandler);
        } else {
            return; // If element does not exist, no operation will be performed}

        // Cleanup function: remove the event listener when the component is uninstalled or dependencies change return () => {
            if (element) { //Check again if element exists, just in case element.removeEventListener('focusout', blurHandler);
            }
        };
    }, [ref.current, blurHandler]); // Dependencies include ref.current and blurHandler

    return null;
}

Code analysis and precautions:

  1. useCallback wraps the event handler function: blurHandler is wrapped by useCallback, which ensures that the reference of blurHandler remains stable during each rendering when ref.current remains unchanged. This is very important for useEffect's dependency optimization to avoid unnecessary event listener re-registration.
  2. dependencies of useEffect:
    • ref.current: useEffect is re-run when the DOM element pointed to by ref changes (although this usually does not happen in EditorProvider, as a best practice, it should be included).
    • blurHandler: Although we use useCallback, if blurHandler internally relies on external variables and these variables change, the reference of blurHandler will also change. At this time, useEffect needs to be re-run to register a new event handling function.
  3. Cleanup function: The function returned by useEffect is a cleanup function. It will run when the component is unloaded or before useEffect's dependencies change and it is re-executed. Here, we removed the focusout event listener added previously to prevent memory leaks.
  4. focusout vs focusin: Similarly, the focusin event is the bubbling version of the focus event. If you need to monitor the focus acquisition behavior of child elements on the parent element, you can use focusin.
  5. Condition check: Inside useEffect, always check if ref.current is null. During the initial stages of component mounting, ref.current may not have been assigned a value yet.

Summarize

In React, sharing refs through Context is a powerful pattern for managing DOM interactions between complex components. When it comes to listening for focus events on these shared refs, it's crucial to understand the difference between blur and focusout (or focus and focusin). The bubbling nature of the focusout event makes it ideal for capturing the out-of-focus behavior of child elements on a parent element. Combined with the correct use of useEffect and useCallback, we can build a robust event listening mechanism without memory leaks.

The above is the detailed content of A practical guide to managing Ref and handling focus events through Context in React. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

JavaScript realizes click-through image switching effect: professional tutorial JavaScript realizes click-through image switching effect: professional tutorial Sep 18, 2025 pm 01:03 PM

This article will introduce how to use JavaScript to achieve the effect of clicking on images. The core idea is to use HTML5's data-* attribute to store the alternate image path, and listen to click events through JavaScript, dynamically switch the src attributes, thereby realizing image switching. This article will provide detailed code examples and explanations to help you understand and master this commonly used interactive effect.

How to get the user's location with the Geolocation API in JavaScript? How to get the user's location with the Geolocation API in JavaScript? Sep 21, 2025 am 06:19 AM

First, check whether the browser supports GeolocationAPI. If supported, call getCurrentPosition() to get the user's current location coordinates, and obtain the latitude and longitude values ??through successful callbacks. At the same time, provide error callback handling exceptions such as denial permission, unavailability of location or timeout. You can also pass in configuration options to enable high precision, set the timeout time and cache validity period. The entire process requires user authorization and corresponding error handling.

How to create a repeating interval with setInterval in JavaScript How to create a repeating interval with setInterval in JavaScript Sep 21, 2025 am 05:31 AM

To create a repetition interval in JavaScript, you need to use the setInterval() function, which will repeatedly execute functions or code blocks at specified milliseconds intervals. For example, setInterval(()=>{console.log("Execute every 2 seconds");},2000) will output a message every 2 seconds until it is cleared by clearInterval(intervalId). It can be used in actual applications to update clocks, poll servers, etc., but pay attention to the minimum delay limit and the impact of function execution time, and clear the interval in time when no longer needed to avoid memory leakage. Especially before component uninstallation or page closing, ensure that

The Nuxt 3 Composition API Explained The Nuxt 3 Composition API Explained Sep 20, 2025 am 03:00 AM

Nuxt3's Composition API core usage includes: 1. definePageMeta is used to define page meta information, such as title, layout and middleware, which need to be called directly in it and cannot be placed in conditional statements; 2. useHead is used to manage page header tags, supports static and responsive updates, and needs to cooperate with definePageMeta to achieve SEO optimization; 3. useAsyncData is used to securely obtain asynchronous data, automatically handle loading and error status, and supports server and client data acquisition control; 4. useFetch is an encapsulation of useAsyncData and $fetch, which automatically infers the request key to avoid duplicate requests

Number formatting in JavaScript: Use toFixed() method to retain fixed decimal places Number formatting in JavaScript: Use toFixed() method to retain fixed decimal places Sep 16, 2025 am 11:57 AM

This tutorial explains in detail how to format numbers into strings with fixed two decimals in JavaScript, even integers can be displayed in the form of "#.00". We will focus on the use of the Number.prototype.toFixed() method, including its syntax, functionality, sample code, and key points to be noted, such as its return type always being a string.

How to copy text to the clipboard in JavaScript? How to copy text to the clipboard in JavaScript? Sep 18, 2025 am 03:50 AM

Use the writeText method of ClipboardAPI to copy text to the clipboard, it needs to be called in security context and user interaction, supports modern browsers, and the old version can be downgraded with execCommand.

How to create a multi-line string in JavaScript? How to create a multi-line string in JavaScript? Sep 20, 2025 am 06:11 AM

TheBestAtOrreatEamulti-LinestringinjavascriptSisingStisingTemplatalalswithbacktTicks, whichpreserveTicks, WhichpreserveReKeAndEExactlyAswritten.

How to create and use Immediately Invoked Function Expressions (IIFE) in JavaScript How to create and use Immediately Invoked Function Expressions (IIFE) in JavaScript Sep 21, 2025 am 05:04 AM

AnIIFE(ImmediatelyInvokedFunctionExpression)isafunctionthatrunsassoonasitisdefined,createdbywrappingafunctioninparenthesesandimmediatelyinvokingit,whichpreventsglobalnamespacepollutionandenablesprivatescopethroughclosure;itiswrittenas(function(){/cod

See all articles