This repository was archived by the owner on Nov 20, 2020. It is now read-only.
This repository was archived by the owner on Nov 20, 2020. It is now read-only.
There is a bug when my filename is "switch" #102
Open
Description
This is my React component
import React, { FC, useState, useEffect, CSSProperties } from 'react'
import classNames from 'classnames'
import { getPrefixCls } from '@util'
const prefixCls = getPrefixCls('switch')
export type SwitchSize = 'small' | 'defaut'
export type SwitchChangeEventHandler = (
checked: boolean,
event: React.MouseEvent<HTMLButtonElement>,
) => void
export type SwitchClickEventHandler = SwitchChangeEventHandler
export interface SwitchProps
extends Omit<React.HTMLAttributes<HTMLButtonElement>, 'onChange' | 'onClick'> {
/** 开关大小 */
size?: SwitchSize
/** Switch 器类名 */
className?: string
/** 指定当前是否选中 */
checked?: boolean
/** 初始是否选中 */
defaultChecked?: boolean
title?: string
/** 是否禁用 */
disabled?: boolean
/** 变化时回调函数 */
onChange?: SwitchChangeEventHandler
/** 点击时回调函数 */
onClick?: SwitchClickEventHandler
style?: CSSProperties
}
const fixControlledValue = (value: boolean | undefined): boolean => {
if (typeof value === 'undefined' || value === null) {
return false
}
return value
}
export const Switch: FC<SwitchProps> = (props: SwitchProps) => {
const {
className,
size,
disabled,
checked,
onClick,
onChange,
defaultChecked,
...restProps
} = props
const [checkedState, setCheckState] = useState<boolean>(fixControlledValue(defaultChecked))
const classes = classNames(prefixCls, className, {
[`${prefixCls}-${size}`]: size,
[`${prefixCls}-checked`]: checkedState,
[`${prefixCls}-disabled`]: disabled,
})
useEffect(() => {
if (typeof checked !== 'undefined' && checked !== null) {
setCheckState(checked)
}
}, [checked])
const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
setCheckState(!checkedState)
onClick?.(!checked, e)
onChange?.(!checked, e)
}
return (
<button
{...restProps}
type="button"
className={classes}
disabled={disabled}
role="switch"
aria-checked={checkedState}
onClick={handleClick}
>
<div className={`${prefixCls}-handle`} />
</button>
)
}
Switch.displayName = 'Switch'
Switch.defaultProps = {
disabled: false,
}
export default Switch
my docs
import { Meta, Story, Props, Preview } from '@storybook/addon-docs/blocks'
import Switch from '../Switch'
import '../style/index.less'
<Meta
title="组件|Switch "
component={Switch}
/>
> 开关选择器。
## 何时使用
- 需要表示开关状态/两种状态之间的切换时;
- 和 `checkbox`的区别是,切换 `switch `会直接触发状态改变,而 `checkbox` 一般用于状态标记,需要和提交操作配合
## 基本
<Preview>
<Story name="基本">
<div className="doc-wrapper">
<Switch />
</div>
</Story>
</Preview>
## 不可用
<Preview>
<Story name="不可用">
<div className="doc-wrapper">
<Switch disabled checked />
</div>
</Story>
</Preview>
## 两种大小
<Preview>
<Story name="两种大小">
<div className="doc-wrapper">
<Switch checked />
<Switch size={'small'} checked />
</div>
</Story>
</Preview>
## API
<Story name="API" />
<Props of={Switch} />
Metadata
Metadata
Assignees
Labels
No labels