Skip to content

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

参数说明类型默认值是否必填
idSwitch组件idstring-
nameSwitch组件namestring-
checkedSwitch是否为打开状态boolean-
disabled是否禁用booleanfalse
classNameSwitch组件的类名string-
styleSwitch组件的样式CSSProperties-
textSwitch组件上显示的文字{ active: ReactNode; inactive: ReactNode }-
colorSwitch组件的颜色string|{ active: string; inactive: string }-
onChange当Switch组件状态改变时触发的回调(bl: boolean, e: React.ChangeEvent<HTMLInputElement>) => void-