块编辑器开发文档

WithFocusOutside

💡 云策文档标注

概述

withFocusOutside 是一个 React 高阶组件,用于在焦点离开元素时触发行为。它解决了 React 中 blur 事件在相同上下文内焦点转移时也会触发的问题,封装了判断焦点是否真正离开元素的逻辑。

关键要点

  • withFocusOutside 是一个 React 高阶组件,用于处理焦点离开元素的行为。
  • 它通过封装逻辑来区分焦点是否真正离开元素,避免在相同上下文内焦点转移时误触发。
  • 使用时需要将原始组件用 withFocusOutside 包装,并在组件类上定义 handleFocusOutside 实例方法。
  • 注意:withFocusOutside 必须仅用于包装 Component 类。

代码示例

import { withFocusOutside, TextControl } from '@wordpress/components';

const MyComponentWithFocusOutside = withFocusOutside(
    class extends React.Component {
        handleFocusOutside() {
            console.log( 'Focus outside' );
        }

        render() {
            return (
                <div>
                    <TextControl onChange={ () => {} } />
                    <TextControl onChange={ () => {} } />
                </div>
            );
        }
    }
);

注意事项

在示例中,handleFocusOutside 函数仅在焦点离开元素时被调用,不会在两个输入框之间转移焦点时触发。


📄 原文内容

withFocusOutside is a React higher-order component to enable behavior to occur when focus leaves an element. Since a blur event will fire in React even when focus transitions to another element in the same context, this higher-order component encapsulates the logic necessary to determine if focus has truly left the element.

Usage

Wrap your original component with withFocusOutside, defining a handleFocusOutside instance method on the component class.

Note: withFocusOutside must only be used to wrap the Component class.

import { withFocusOutside, TextControl } from '@wordpress/components';

const MyComponentWithFocusOutside = withFocusOutside(
    class extends React.Component {
        handleFocusOutside() {
            console.log( 'Focus outside' );
        }

        render() {
            return (
                <div>
                    <TextControl onChange={ () => {} } />
                    <TextControl onChange={ () => {} } />
                </div>
            );
        }
    }
);

In the above example, the handleFocusOutside function is only called if focus leaves the element, and not if transitioning focus between the two inputs.