使用React + TS 封装Switch组件
import React, { useMemo, FC, memo, useState} from "react";
import './Switch.module.less'
import { SwitchProps, SwitchStyle } from "./interface";
const Switch: FC<SwitchProps> = memo((props) => {
const {width, activeColor, inActiveColor} = props;
const [isActive, setIsActive] = useState(false);
const refs:React.MutableRefObject<any> = useRef(null) ;
const ballClick = () => {
if (width) {
if (isActive === false) {
refs.current!.style.transform = `translateX(${(width - 27)}px)`
setIsActive(!isActive)
} else {
refs.current.style.transform = `translateX(0px)`
setIsActive(!isActive)
}
} else {
let widths = switchSize.width?.slice(0, 2)
if (isActive === false) {
refs.current!.style.transform = `translateX(${(widths - 27)}px)`
setIsActive(!isActive)
} else {
refs.current!.style.transform = `translateX(0px)`
setIsActive(!isActive)
}
}
}
const switchSize = useMemo(() => {
var size: SwitchStyle = {
width: '65px',
backgroundColor: "#409EFF"
};
if (width) {
size.width = width + 'px'
}
if (activeColor) {
size.backgroundColor = activeColor + ""
}
return size;
}, [disabled, width, activeColor])
const failSize = useMemo(() => {
var size: SwitchStyle = {
width: '65px',
backgroundColor: "#C0CCDA"
};
if (width) {
size.width = width + 'px'
}
if (inActiveColor) {
size.backgroundColor = inActiveColor + ""
}
return size;
}, [ width, inActiveColor,])
return (
<div>
<div className="switch"
style={isActive ? switchSize as any : failSize as any}
onClick={() => ballClick()}>
<div className="ball" ref={refs}></div>
</div>
</div>
)
})
export default Switch;