块编辑器开发文档

💡 云策文档标注

概述

Disabled 是一个 WordPress 组件,用于禁用后代可聚焦元素并阻止指针交互。它通过包装子组件实现禁用效果,并支持通过上下文检测禁用状态。

关键要点

  • Disabled 组件可禁用所有后代可聚焦元素,防止用户交互。
  • 通过 Disabled.Context 上下文,组件可以检测是否被禁用,以调整样式或行为。
  • 在不支持 inert HTML 属性的浏览器中,建议使用 WICG polyfill 以确保兼容性。

代码示例

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

const MyDisabled = () => {
    const [ isDisabled, setIsDisabled ] = useState( true );

    let input = (
        <TextControl
            __next40pxDefaultSize
            label="Input"
            onChange={ () => {} }
        />
    );
    if ( isDisabled ) {
        input = <Disabled>{ input }</Disabled>;
    }

    const toggleDisabled = () => {
        setIsDisabled( ( state ) => ! state );
    };

    return (
        <div>
            { input }
            <Button variant="primary" onClick={ toggleDisabled }>
                Toggle Disabled
            </Button>
        </div>
    );
};

注意事项

在不支持 inert HTML 属性的浏览器中,Disabled 组件可能无法正常工作,建议添加官方 WICG polyfill 以提升兼容性。


📄 原文内容

Disabled is a component which disables descendant tabbable elements and prevents pointer interaction.

Usage

Assuming you have a form component, you can disable all form inputs by wrapping the form with <Disabled>.

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

const MyDisabled = () => {
    const [ isDisabled, setIsDisabled ] = useState( true );

    let input = (
        <TextControl
            __next40pxDefaultSize
            label="Input"
            onChange={ () => {} }
        />
    );
    if ( isDisabled ) {
        input = <Disabled>{ input }</Disabled>;
    }

    const toggleDisabled = () => {
        setIsDisabled( ( state ) => ! state );
    };

    return (
        <div>
            { input }
            <Button variant="primary" onClick={ toggleDisabled }>
                Toggle Disabled
            </Button>
        </div>
    );
};

A component can detect if it has been wrapped in a <Disabled /> by accessing its context using Disabled.Context.

function CustomButton( props ) {
    const isDisabled = useContext( Disabled.Context );
    return <button { ...props } style={ { opacity: isDisabled ? 0.5 : 1 } } />;
}

Note: this component may not behave as expected in browsers that don’t support the inert HTML attribute. We recommend adding the official WICG polyfill when using this component in your project.

Props

The component accepts the following props:

isDisabled

Whether to disable all the descendant fields. Defaults to true.

  • Type: Boolean
  • Required: No
  • Default: true