使用react + ts 封装的一个Switch开关的组件,并且可以实现自定义开启和关闭时的背景颜色
在index.tsx 文件中,编写代码:
import React, { useMemo, FC, memo, useState} from "react";
import './Switch.module.less'
import { SwitchProps, SwitchStyle } from "./interface";
// 控制开关的 true(在左边 为 关闭) false(圆球在右边 为开启)
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;
在interface.ts文件中
export interface SwitchProps{
// 自定义switch接口
/**
* @description switch宽度(像素)
* @default 65px
*/
width?: any;
/**
* @description switch 打开时的背景色
* @default #409EFF
*/
activeColor?:String;
/**
* @description switch 关闭时的背景色
* @default #C0CCDA
*/
inActiveColor?:String;
}
export interface SwitchStyle{
// 样式接口
type?:String;
width?: any;
activeColor?:String;
inActiveColor?:String;
}
例子:使用组件时的例子
首先引入组件的文件
<Switch activeColor="#13ce66" inActiveColor="#ff4949"></Switch>
css样式我就不写啦~~~