|
1 | 1 | import classNames from 'classnames'; |
2 | | -import useMergedState from '@rc-component/util/lib/hooks/useMergedState'; |
| 2 | +import { useControlledState, useEvent } from '@rc-component/util'; |
3 | 3 | import warning from '@rc-component/util/lib/warning'; |
4 | 4 | import React from 'react'; |
5 | 5 | import useItems from './hooks/useItems'; |
6 | 6 | import type { CollapseProps } from './interface'; |
7 | 7 | import CollapsePanel from './Panel'; |
8 | 8 | import pickAttrs from '@rc-component/util/lib/pickAttrs'; |
9 | 9 |
|
10 | | -function getActiveKeysArray(activeKey: React.Key | React.Key[]) { |
| 10 | +function getActiveKeysArray(activeKey: React.Key | React.Key[]): React.Key[] { |
11 | 11 | let currentActiveKey = activeKey; |
12 | 12 | if (!Array.isArray(currentActiveKey)) { |
13 | 13 | const activeKeyType = typeof currentActiveKey; |
@@ -38,27 +38,27 @@ const Collapse = React.forwardRef<HTMLDivElement, CollapseProps>((props, ref) => |
38 | 38 |
|
39 | 39 | const collapseClassName = classNames(prefixCls, className); |
40 | 40 |
|
41 | | - const [activeKey, setActiveKey] = useMergedState<React.Key | React.Key[], React.Key[]>([], { |
42 | | - value: rawActiveKey, |
43 | | - onChange: (v) => onChange?.(v as React.Key[]), |
44 | | - defaultValue: defaultActiveKey, |
45 | | - postState: getActiveKeysArray, |
46 | | - }); |
47 | | - |
48 | | - const onItemClick = (key: React.Key) => |
49 | | - setActiveKey(() => { |
50 | | - if (accordion) { |
51 | | - return activeKey[0] === key ? [] : [key]; |
52 | | - } |
| 41 | + const [internalActiveKey, setActiveKey] = useControlledState<React.Key[] | React.Key>( |
| 42 | + defaultActiveKey, |
| 43 | + rawActiveKey, |
| 44 | + ); |
| 45 | + const activeKey = getActiveKeysArray(internalActiveKey); |
53 | 46 |
|
54 | | - const index = activeKey.indexOf(key); |
55 | | - const isActive = index > -1; |
56 | | - if (isActive) { |
57 | | - return activeKey.filter((item) => item !== key); |
58 | | - } |
| 47 | + const triggerActiveKey = useEvent((next) => { |
| 48 | + const nextKeys = getActiveKeysArray(next); |
| 49 | + setActiveKey(nextKeys); |
| 50 | + onChange?.(nextKeys); |
| 51 | + }); |
59 | 52 |
|
60 | | - return [...activeKey, key]; |
61 | | - }); |
| 53 | + const onItemClick = (key: React.Key) => { |
| 54 | + if (accordion) { |
| 55 | + triggerActiveKey(activeKey[0] === key ? [] : [key]); |
| 56 | + } else { |
| 57 | + triggerActiveKey( |
| 58 | + activeKey.includes(key) ? activeKey.filter((item) => item !== key) : [...activeKey, key], |
| 59 | + ); |
| 60 | + } |
| 61 | + }; |
62 | 62 |
|
63 | 63 | // ======================== Children ======================== |
64 | 64 | warning( |
|
0 commit comments