withConstrainedTabbing 是一个 React 高阶组件,用于在组件内限制使用 Tab 键进行键盘导航的能力。出于无障碍访问的考虑,某些 UI 组件需要限制 Tab 导航,例如模态对话框或类似的 UI。建议仅在已通过其他方式实现从包装组件中导航出去的情况下使用该组件,通常是通过按 Escape 键或使用特定的 UI 控件(例如“关闭”按钮)来实现。

用法

使用 withConstrainedTabbing 包装你的原始组件。

import { useState } from 'react';
import {
    withConstrainedTabbing,
    TextControl,
    Button,
} from '@wordpress/components';

const ConstrainedTabbing = withConstrainedTabbing(
    ( { children } ) => children
);

const MyComponentWithConstrainedTabbing = () => {
    const [ isConstrainedTabbing, setIsConstrainedTabbing ] = useState( false );
    let form = (
        <form>
            <TextControl
                label="Input 1"
                onChange={ () => {} }
            />
            <TextControl
                label="Input 2"
                onChange={ () => {} }
            />
        </form>
    );
    if ( isConstrainedTabbing ) {
        form = <ConstrainedTabbing>{ form }</ConstrainedTabbing>;
    }

    const toggleConstrain = () => {
        setIsConstrainedTabbing( ( state ) => ! state );
    };

    return (
        <div>
            { form }
            <Button variant="secondary" onClick={ toggleConstrain }>
                { isConstrainedTabbing ? 'Disable' : 'Enable' } constrain
                tabbing
            </Button>
        </div>
    );
};