Switch
Switching Selector.
When To Use#
If you need to represent the switching between two states or on-off state.
The difference between
SwitchandCheckboxis thatSwitchwill trigger a state change directly when you toggle it, whileCheckboxis generally used for state marking, which should work in conjunction with submit operation.
Examples
import { Switch } from 'antd';
function onChange(checked) {
console.log(`switch to ${checked}`);
}
ReactDOM.render(<Switch defaultChecked onChange={onChange} />, mountNode);import { Switch } from 'antd';
import { CloseOutlined, CheckOutlined } from '@ant-design/icons';
ReactDOM.render(
<>
<Switch checkedChildren="开启" unCheckedChildren="关闭" defaultChecked />
<br />
<Switch checkedChildren="1" unCheckedChildren="0" />
<br />
<Switch
checkedChildren={<CheckOutlined />}
unCheckedChildren={<CloseOutlined />}
defaultChecked
/>
</>,
mountNode,
);import { Switch } from 'antd';
ReactDOM.render(
<>
<Switch loading defaultChecked />
<br />
<Switch size="small" loading />
</>,
mountNode,
);import { Switch, Button } from 'antd';
class App extends React.Component {
state = {
disabled: true,
};
toggle = () => {
this.setState({
disabled: !this.state.disabled,
});
};
render() {
return (
<>
<Switch disabled={this.state.disabled} defaultChecked />
<br />
<Button type="primary" onClick={this.toggle}>
Toggle disabled
</Button>
</>
);
}
}
ReactDOM.render(<App />, mountNode);import { Switch } from 'antd';
ReactDOM.render(
<>
<Switch defaultChecked />
<br />
<Switch size="small" defaultChecked />
</>,
mountNode,
);API#
| Property | Description | Type | Default |
|---|---|---|---|
| autoFocus | Whether get focus when component mounted | boolean | false |
| checked | Determine whether the Switch is checked | boolean | false |
| checkedChildren | The content to be shown when the state is checked | string | ReactNode | - |
| defaultChecked | Whether to set the initial state | boolean | false |
| disabled | Disable switch | boolean | false |
| loading | Loading state of switch | boolean | false |
| size | The size of the Switch, options: default small | string | default |
| unCheckedChildren | The content to be shown when the state is unchecked | string | ReactNode | - |
| onChange | Trigger when the checked state is changing | function(checked: boolean, event: Event) | - |
| onClick | Trigger when clicked | function(checked: boolean, event: Event) | - |
| className | The additional class to Switch | string | - |
Methods#
| Name | Description |
|---|---|
| blur() | Remove focus |
| focus() | Get focus |