ToggleControl 是 WordPress 组件库中的一个 React 组件,用于生成切换开关用户界面,常用于控制布尔状态设置。它支持标签、帮助文本、禁用状态等属性,便于在 Gutenberg 编辑器或自定义块中集成。
import { useState } from 'react';
import { ToggleControl } from '@wordpress/components';
const MyToggleControl = () => {
const [ hasFixedBackground, setHasFixedBackground ] = useState( false );
return (
<ToggleControl
label="Fixed Background"
help={
hasFixedBackground
? 'Has fixed background.'
: 'No fixed background.'
}
checked={ hasFixedBackground }
onChange={ (newValue) => {
setHasFixedBackground( newValue );
} }
/>
);
};ToggleControl is used to generate a toggle user interface.
Render a user interface to change fixed background setting.
import { useState } from 'react';
import { ToggleControl } from '@wordpress/components';
const MyToggleControl = () => {
const [ hasFixedBackground, setHasFixedBackground ] = useState( false );
return (
<ToggleControl
label="Fixed Background"
help={
hasFixedBackground
? 'Has fixed background.'
: 'No fixed background.'
}
checked={ hasFixedBackground }
onChange={ (newValue) => {
setHasFixedBackground( newValue );
} }
/>
);
};
The component accepts the following props:
If this property is added, a label will be generated using label property as the content.
StringIf this property is added, a help text will be generated using help property as the content.
For controlled components the help prop can also be a function which will return a help text
dynamically depending on the boolean checked parameter.
String|Element|FunctionIf checked is true the toggle will be checked. If checked is false the toggle will be unchecked.
If no value is passed the toggle will be an uncontrolled component with unchecked initial value.
BooleanIf disabled is true the toggle will be disabled and apply the appropriate styles.
BooleanA function that receives the checked state (boolean) as input.
functionThe class that will be added with components-base-control and components-toggle-control to the classes of the wrapper div. If no className is passed only components-base-control and components-toggle-control are used.
String