Switch开关
开关选择器。
何时使用#
需要表示开关状态/两种状态之间的切换时;
和
checkbox
的区别是,切换switch
会直接触发状态改变,而checkbox
一般用于状态标记,需要和提交操作配合。
代码演示
TypeScript
JavaScript
import { Switch } from 'antd';
import React from 'react';
const onChange = (checked: boolean) => {
console.log(`switch to ${checked}`);
};
const App: React.FC = () => <Switch defaultChecked onChange={onChange} />;
export default App;
TypeScript
JavaScript
import { CheckOutlined, CloseOutlined } from '@ant-design/icons';
import { Switch } from 'antd';
import React from 'react';
const App: React.FC = () => (
<>
<Switch checkedChildren="开启" unCheckedChildren="关闭" defaultChecked />
<br />
<Switch checkedChildren="1" unCheckedChildren="0" />
<br />
<Switch
checkedChildren={<CheckOutlined />}
unCheckedChildren={<CloseOutlined />}
defaultChecked
/>
</>
);
export default App;
TypeScript
JavaScript
import { Switch } from 'antd';
import React from 'react';
const App: React.FC = () => (
<>
<Switch loading defaultChecked />
<br />
<Switch size="small" loading />
</>
);
export default App;
TypeScript
JavaScript
import { Button, Switch } from 'antd';
import React, { useState } from 'react';
const App: React.FC = () => {
const [disabled, setDisabled] = useState(true);
const toggle = () => {
setDisabled(!disabled);
};
return (
<>
<Switch disabled={disabled} defaultChecked />
<br />
<Button type="primary" onClick={toggle}>
Toggle disabled
</Button>
</>
);
};
export default App;
TypeScript
JavaScript
import { Switch } from 'antd';
import React from 'react';
const App: React.FC = () => (
<>
<Switch defaultChecked />
<br />
<Switch size="small" defaultChecked />
</>
);
export default App;
API#
参数 | 说明 | 类型 | 默认值 |
---|---|---|---|
autoFocus | 组件自动获取焦点 | boolean | false |
checked | 指定当前是否选中 | boolean | false |
checkedChildren | 选中时的内容 | ReactNode | - |
className | Switch 器类名 | string | - |
defaultChecked | 初始是否选中 | boolean | false |
disabled | 是否禁用 | boolean | false |
loading | 加载中的开关 | boolean | false |
size | 开关大小,可选值:default small | string | default |
unCheckedChildren | 非选中时的内容 | ReactNode | - |
onChange | 变化时的回调函数 | function(checked: boolean, event: Event) | - |
onClick | 点击时的回调函数 | function(checked: boolean, event: Event) | - |
方法#
名称 | 描述 |
---|---|
blur() | 移除焦点 |
focus() | 获取焦点 |