import React, { CSSProperties, HTMLAttributes, ReactNode } from 'react' import classnames from 'classnames' import RcSwitch, { SwitchChangeEventHandler } from 'rc-switch' import { ComponentSize, usePrefix } from '../ConfigProvider' import { concat } from '../utils' import { useFormSize } from '../Form/defs' import { LoadingThinIcon } from '../icons' import { useAnimationCls } from '../utils/hooks' import { WithRef } from '../utils/type' export type SwitchProps = { /** * 大小 * * 'large' 和 'default' 效果一样 * @default 'default' */ size?: ComponentSize /** 是否 checked */ checked?: boolean /** checked 状态变化后触发的回调 */ onChange?: (checked: boolean) => void /** * 默认 check 状态 * @default false */ defaultChecked?: boolean /** * checked 状态下的内容 * * 使用建议:不要在 size 为 'small' 的时候用此属性, 空间不够容纳更小的内容 */ checkedChildren?: ReactNode /** * unchecked 状态下的内容 * * 使用建议:不要在 size 为 'small' 的时候用此属性, 空间不够容纳更小的内容 */ unCheckedChildren?: ReactNode /** * @default false */ disabled?: boolean rootHtmlProps?: WithRef, HTMLButtonElement> className?: string style?: CSSProperties /** * @default false */ loading?: boolean } export function Switch(props: SwitchProps) { const { rootHtmlProps, className, size, onChange, style, loading = false, disabled = false, ...rest } = props const prefix = usePrefix('switch') const formSize = useFormSize(size) const sizeCls = concat(prefix, formSize) const { spinCls } = useAnimationCls() function renderHandle() { if (loading) { return (
) } return
} function handleChange(nextChecked: boolean, event: React.MouseEvent) { rootHtmlProps?.onChange?.(event) if (event.defaultPrevented) return onChange?.(nextChecked) } return ( , 'onChange' | 'onClick'>} // 此 as 解决 rc-switch 会给 keyboard event 的问题,button 无法触发键盘事件 onChange={(onChange || rootHtmlProps?.onChange) && handleChange as SwitchChangeEventHandler} className={classnames(className, sizeCls, rootHtmlProps?.className)} style={{ ...style, ...rootHtmlProps?.style }} disabled={disabled || loading} {...rest} /> ) }