-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.tsx
109 lines (95 loc) · 2.7 KB
/
index.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import { useEffect, useMemo, useRef, useState, ReactNode } from "react";
import styles from "./index.module.scss";
import { StepsFormProvider } from "./context";
import StepForm from "./StepForm";
type StepsFormProps = {
/**
* 表单内容,每个子元素需要时一个StepForm组件
*/
children: ReactNode;
/**
* 默认初始显示第几步
*/
defaultCurrent?: number;
/**
* 切换步骤时的回调
* @param current
* @returns
*/
onCurrentChange?: (current: number) => void;
/**
* 最后一步提交函数
* @param values
* @returns
*/
onFinish?: (values: any) => Promise<boolean | void>;
};
const StepsForm = ({
children,
defaultCurrent = 0,
onFinish,
}: StepsFormProps) => {
const container = useRef<HTMLDivElement>(); // 容器
const wrapperRef = useRef<HTMLDivElement>(); // 滚动容器
const [currentIndex, setCurrentIndex] = useState<number>(defaultCurrent); // 当前显示第几步
const [containerWidth, setContainerWidth] = useState<number>(); // 容器宽度
// 子元素个数
const childrenCount = useMemo(() => {
return React.Children.count(children);
}, [children]);
// 保存每一步的值
const [values, setValues] = useState<any>();
useEffect(() => {
// 初始化容器宽度
setContainerWidth(container.current?.clientWidth);
// 监听窗口变化
window.addEventListener("resize", () => {
setContainerWidth(container.current?.clientWidth);
});
return () => {
window.removeEventListener("resize", () => {
setContainerWidth(container.current?.clientWidth);
});
};
}, []);
useEffect(() => {
// 每次切换都滚动到顶部
wrapperRef.current?.children[currentIndex].scrollTo(0, 0);
}, [currentIndex]);
return (
<StepsFormProvider
value={{
currentIndex,
setCurrentIndex,
childrenCount,
onLastFinish: onFinish,
values,
setValues,
}}
>
<div className={styles.stepsContainer} ref={container as any}>
{containerWidth && (
<div
className="wrapper"
ref={wrapperRef as any}
style={{
transform: `translateX(${
-currentIndex * (containerWidth || 343)
}px)`,
}}
>
{React.Children.map(children, (child, index) => {
return (
<div className="item" style={{ width: containerWidth + "px" }}>
{React.cloneElement(child as React.ReactElement, {})}
</div>
);
})}
</div>
)}
</div>
</StepsFormProvider>
);
};
StepsForm.StepForm = StepForm;
export default StepsForm;