Disabled 是一个组件,用于禁用可聚焦的后代元素并阻止指针交互。
用法
假设你有一个表单组件,你可以通过将表单包裹在 <Disabled> 中来禁用所有表单输入。
import { useState } from 'react';
import { Button, Disabled, TextControl } from '@wordpress/components';
const MyDisabled = () => {
const [ isDisabled, setIsDisabled ] = useState( true );
let input = (
<TextControl
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>
);
};
组件可以通过使用 Disabled.Context 访问其 上下文 来检测它是否被包裹在 <Disabled /> 中。
function CustomButton( props ) {
const isDisabled = useContext( Disabled.Context );
return <button { ...props } style={ { opacity: isDisabled ? 0.5 : 1 } } />;
}
注意:在不支持 inert HTML 属性 的浏览器中,此组件可能无法按预期工作。我们建议在项目中使用时添加 官方 WICG polyfill。
属性
该组件接受以下属性:
isDisabled
是否禁用所有后代字段。默认为 true。
- 类型:
Boolean - 必需:否
- 默认值:
true