---
name: "Switch"
mode: "component"
versionRequirements:
  - { name: "@ray-js/ray", version: "0.5.10" }
title: "Switch - 开关选择器"
---

## Switch

> [VERSION] @ray-js/ray >= 0.5.10

### 描述

开关选择器，用于在两种互斥状态间切换。

### 属性

| 属性 | 类型 | 必填 | 默认值 | 描述 |
| --- | --- | --- | --- | --- |
| `checked` | `boolean` | 否 | - | 当前是否选中 |
| `disabled` | `boolean` | 否 | `false` | 是否禁用 |
| `color` | `string` | 否 | `"#007AFF"` | 开关颜色，同 CSS 的 color |
| `type` | `"switch" \| "checkbox"` | 否 | `"switch"` | 样式类型，可选 switch、checkbox |
| `name` | `string` | 否 | - | 表单控件名称，提交表单时作为键名 |
| `onChange` | `(event: SwitchChangeEvent) => void` | 否 | - | 选中状态改变时触发，detail 含 value |

### 引用对象

##### `interface` SwitchChangeEvent

| 属性 | 类型 | 描述 |
| --- | --- | --- |
| `type` | `"change"` | 事件类型 |
| `detail` | `SwitchChangeDetail` | 事件数据，通过 detail.value 获取当前取值 |

##### `interface` SwitchChangeDetail

| 属性 | 类型 | 描述 |
| --- | --- | --- |
| `value` | `boolean` | 当前选中状态 |

##### `interface` BaseEvent

| 属性 | 类型 | 描述 |
| --- | --- | --- |
| `type` | `string` | 事件类型 |
| `timeStamp` | `number` | 页面打开到触发事件所经过的毫秒数 |
| `target` | `Target` | 触发事件的源组件 |
| `currentTarget` | `Target` | 当前组件的一些属性值集合 |
| `mark` | `any` | 事件标记数据 |

##### `interface` Target

| 属性 | 类型 | 描述 |
| --- | --- | --- |
| `id` | `string` | 事件源组件的id |
| `dataset` | `Record<string, unknown>` | 事件源组件上的 `dataset` 自定义属性组成的集合 |


### 示例代码

#### 基础用法

```tsx
import React from 'react';
import { Switch, View } from '@ray-js/ray';

export default function () {
  return (
    <View style={{ padding: '20px' }}>
      <Switch
        onChange={(e) => {
          console.log('Switch 改变:', e.detail.value);
        }}
      />
    </View>
  );
}
```

#### 不同状态

```tsx
import React, { useState } from 'react';
import { Switch, View, Text } from '@ray-js/ray';

export default function () {
  const [checked, setChecked] = useState(false);

  return (
    <View style={{ padding: '20px' }}>
      <View style={{ marginBottom: '16px' }}>
        <Text>受控开关:</Text>
        <Switch
          checked={checked}
          onChange={(e) => {
            console.log('Switch 改变:', e.detail.value);
            setChecked(e.detail.value);
          }}
          style={{ marginTop: '8px' }}
        />
        <Text style={{ marginTop: '8px' }}>当前状态: {checked ? '开' : '关'}</Text>
      </View>
      <View style={{ marginBottom: '16px' }}>
        <Text>自定义颜色:</Text>
        <Switch color="#ff0000" checked style={{ marginTop: '8px' }} />
      </View>
      <View style={{ marginBottom: '16px' }}>
        <Text>禁用状态:</Text>
        <Switch disabled style={{ marginTop: '8px' }} />
      </View>
      <View style={{ marginBottom: '16px' }}>
        <Text>Checkbox 类型:</Text>
        <Switch type="checkbox" checked style={{ marginTop: '8px' }} />
      </View>
    </View>
  );
}
```
