Switch 开关
使用开关切换两种状态之间。
前置条件
在react项目入口文件中引入样式,默认为src/main.tsx。
tsx
import 'ono-react-element/dist/style/Switch.css'基础用法
tsx
import React, { useState } from'react'
import { Switch } from 'ono-react-element'
function App() {
const [checked, setChecked] = useState(false)
return (
<div style={{ width: '100%' }}>
<Switch
checked={checked}
onChange={bl => setChecked(bl)}
/>
</div>
)
}
export default App;自定义文本
tsx
import React, { useState } from'react'
import { Switch } from 'ono-react-element'
function App() {
const [checked, setChecked] = useState(false)
return (
<div style={{ width: '100%' }}>
<Switch
style={{ width: 60, height: 24 }}
checked={checked}
onChange={(value) => setChecked(value)}
text={{
active: <span className="text-white">开</span>,
inactive: <span>关</span>
}}
/>
</div>
)
}
export default App;自定义开关颜色
tsx
import React, { useState } from'react'
import { Switch } from 'ono-react-element'
function App() {
const [checked, setChecked] = useState(false)
return (
<div style={{ width: '100%' }}>
<Switch
style={{ width: 48, height: 24 }}
checked={checked}
onChange={(value) => setChecked(value)}
color={{ active: 'blue', inactive: 'red' }}
/>
</div>
)
}
export default App;API
| 参数 | 说明 | 类型 | 默认值 | 是否必填 |
|---|---|---|---|---|
| id | Switch组件id | string | - | 否 |
| name | Switch组件name | string | - | 否 |
| checked | Switch是否为打开状态 | boolean | - | 是 |
| disabled | 是否禁用 | boolean | false | 否 |
| className | Switch组件的类名 | string | - | 否 |
| style | Switch组件的样式 | CSSProperties | - | 否 |
| text | Switch组件上显示的文字 | { active: ReactNode; inactive: ReactNode } | - | 否 |
| color | Switch组件的颜色 | string|{ active: string; inactive: string } | - | 否 |
| onChange | 当Switch组件状态改变时触发的回调 | (bl: boolean, e: React.ChangeEvent<HTMLInputElement>) => void | - | 否 |