switch.tsx 2.0 KB
Newer Older
B
bjdushoujun 已提交
1
import React, { FunctionComponent, useState, useEffect } from 'react'
O
oasis-cloud 已提交
2

B
bjdushoujun 已提交
3 4 5 6 7 8 9 10 11 12
import bem from '@/utils/bem'

export interface SwitchProps {
  isAsync: boolean
  checked: boolean
  disable: boolean
  activeColor: string
  inactiveColor: string
  activeText: string
  inactiveText: string
B
bjdushoujun 已提交
13 14
  className: string
  style: React.CSSProperties
B
bjdushoujun 已提交
15 16 17 18 19 20 21 22 23 24
  change: (val: boolean, event: React.MouseEvent) => void
}
const defaultProps = {
  isAsync: false,
  checked: false,
  disable: false,
  activeColor: '',
  inactiveColor: '',
  activeText: '',
  inactiveText: '',
B
bjdushoujun 已提交
25
  className: '',
B
bjdushoujun 已提交
26 27 28 29 30 31 32 33 34 35 36
} as SwitchProps
export const Switch: FunctionComponent<Partial<SwitchProps>> = (props) => {
  const {
    isAsync,
    checked,
    disable,
    activeColor,
    inactiveColor,
    activeText,
    inactiveText,
    change,
B
bjdushoujun 已提交
37 38
    className,
    style,
B
bjdushoujun 已提交
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
  } = {
    ...defaultProps,
    ...props,
  }

  const [value, setValue] = useState(false)
  const b = bem('switch')

  useEffect(() => {
    setValue(checked)
  }, [checked])

  const classes = () => {
    return `${b()} ${value ? 'switch-open' : 'switch-close'} ${
      disable ? `${b()}-disable` : ''
B
bjdushoujun 已提交
54
    } ${`${b()}-base`} ${className}`
B
bjdushoujun 已提交
55 56
  }

B
bjdushoujun 已提交
57 58 59 60 61 62 63 64
  const styles = () => {
    const myStyle = Object.assign(
      {},
      { backgroundColor: value ? activeColor : inactiveColor },
      style || {}
    )

    return myStyle
B
bjdushoujun 已提交
65 66
  }

B
bjdushoujun 已提交
67
  const onClick = (event: React.MouseEvent<Element, MouseEvent>) => {
B
bjdushoujun 已提交
68 69 70 71 72 73 74
    if (disable) return
    if (!isAsync) {
      setValue(!value)
    }
    change && change(!value, event)
  }
  return (
B
bjdushoujun 已提交
75
    <div className={classes()} onClick={(e) => onClick(e)} style={styles()}>
B
bjdushoujun 已提交
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
      <div className="switch-button">
        {!value && <div className="close-line"></div>}
        {activeText && (
          <>
            {value ? (
              <div className={`${b('label')} open`}>{activeText}</div>
            ) : (
              <div className={`${b('label')} close`}>{inactiveText}</div>
            )}
          </>
        )}
      </div>
    </div>
  )
}

Switch.defaultProps = defaultProps
Switch.displayName = 'NutSwitch'