Switch 组件

预览
index.tsx
index.css
1
import { motion } from 'motion/react'
2
import React, { useState } from 'react'
3
import { useEffect } from 'react'
4
import './index.css'
5
6
interface SwitchProps {
7
onChange?: (checked: boolean) => void
8
checked?: boolean
9
style?: React.CSSProperties
10
}
11
12
export default function Switch({ onChange, checked = false, style }: SwitchProps) {
13
const [__checked, setChecked] = useState(checked) // 内部状态
14
15
useEffect(() => {
16
setChecked(checked)
17
}, [checked])
18
19
const __clickHandler = () => {
20
setChecked(!__checked)
21
onChange && onChange(!__checked)
22
}
23
24
return (
25
<label className="super-toggle-switch" style={style}>
26
<button
27
className="super-toggle-container"
28
style={{
29
justifyContent: __checked ? 'flex-end' : 'flex-start',
30
}}
31
onClick={__clickHandler}
32
>
33
<motion.div
34
className="super-toggle-handle"
35
layout
36
style={{ backgroundColor: __checked ? '#e3e6e8' : '#5d666f' }}
37
transition={{
38
type: 'spring',
39
stiffness: 400,
40
damping: 20,
41
}}
42
/>
43
</button>
44
<div>Show Perspective</div>
45
</label>
46
)
47
}
48
专栏首页
到顶
专栏目录