withConstrainedTabbing 是一个 React 高阶组件,用于在组件内限制 Tab 键的键盘导航,常用于模态对话框等需要提升可访问性的 UI 场景。建议仅在已实现其他方式(如 Escape 键或“关闭”按钮)退出限制时使用。
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
__next40pxDefaultSize
label="Input 1"
onChange={ () => {} }
/>
<TextControl
__next40pxDefaultSize
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>
);
};确保在使用 withConstrainedTabbing 时,组件提供了明确的退出方式,以避免键盘焦点被永久限制。
withConstrainedTabbing is a React higher-order component adding the ability to constrain keyboard navigation with the Tab key within a component. For accessibility reasons, some UI components need to constrain Tab navigation, for example modal dialogs or similar UI. Use of this component is recommended only in cases where a way to navigate away from the wrapped component is implemented by other means, usually by pressing the Escape key or using a specific UI control, e.g. a “Close” button.
Wrap your original component with 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
__next40pxDefaultSize
label="Input 1"
onChange={ () => {} }
/>
<TextControl
__next40pxDefaultSize
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>
);
};