FormToggle 是 WordPress 组件库中的一个 React 组件,用于实现开关切换功能,允许用户启用或禁用单个设置。文档提供了设计指南和开发指南,帮助开发者正确使用该组件。
import { useState } from 'react';
import { FormToggle } from '@wordpress/components';
const MyFormToggle = () => {
const [ isChecked, setChecked ] = useState( true );
return (
<FormToggle
checked={ isChecked }
onChange={ () => setChecked( ( state ) => ! state ) }
/>
);
};FormToggle switches a single setting on or off.

Use toggles when you want users to:

Do
Use toggles to switch an option on or off.

Don’t
Don’t use radio buttons for settings that toggle on and off.
Toggles are preferred when the user is not expecting to submit data, as is the case with checkboxes and radio buttons.
When the user slides a toggle thumb (1) to the other side of the track (2) and the state of the toggle changes, it’s been successfully toggled.

Toggles should have clear inline labels so users know exactly what option the toggle controls, and whether the option is enabled or disabled.
Do not include any text (e.g. “on” or “off”) within the toggle element itself. The toggle alone should be sufficient to communicate the state.
When a user switches a toggle, its corresponding action takes effect immediately.
import { useState } from 'react';
import { FormToggle } from '@wordpress/components';
const MyFormToggle = () => {
const [ isChecked, setChecked ] = useState( true );
return (
<FormToggle
checked={ isChecked }
onChange={ () => setChecked( ( state ) => ! state ) }
/>
);
};
The component accepts the following props:
checked: booleanIf 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 unchecked.
disabled: booleanIf disabled is true the toggle will be disabled and apply the appropriate styles.
onChange: ( event: ChangeEvent<HTMLInputElement> ) => voidA callback function invoked when the toggle is clicked.
Radio component.CheckboxControl component.ToggleControl component.