|
1 | | -import { get } from 'lodash-es'; |
2 | 1 | import React, { ReactElement, ReactNode, useEffect, useState } from 'react'; |
| 2 | +import { get } from 'lodash-es'; |
3 | 3 | import Option from '../base/Option'; |
4 | 4 | import OptionGroup from '../base/OptionGroup'; |
5 | 5 | import { getKeyMapping, getValueToOption, type ValueToOption } from '../util/helper'; |
6 | 6 |
|
7 | 7 | import type { SelectKeysType, SelectOption, SelectOptionGroup, SelectValue, TdOptionProps } from '../type'; |
8 | 8 |
|
| 9 | +type OptionValueType = SelectValue<SelectOption>; |
| 10 | + |
9 | 11 | export function isSelectOptionGroup(option: SelectOption): option is SelectOptionGroup { |
10 | 12 | return !!option && 'group' in option && 'children' in option; |
11 | 13 | } |
12 | 14 |
|
13 | | -type OptionValueType = SelectValue<SelectOption>; |
| 15 | +export function isValueSelected(v: SelectValue, key: string, valueType: string, valueKey: string) { |
| 16 | + return valueType === 'value' ? String(v) === String(key) : get(v, valueKey) === key; |
| 17 | +} |
14 | 18 |
|
15 | | -// 处理 options 的逻辑 |
16 | 19 | function useOptions( |
17 | 20 | keys: SelectKeysType, |
18 | 21 | options: SelectOption[], |
@@ -66,9 +69,28 @@ function useOptions( |
66 | 69 | setCurrentOptions(transformedOptions); |
67 | 70 | setTmpPropOptions(transformedOptions); |
68 | 71 |
|
69 | | - setValueToOption(getValueToOption(children as ReactElement, options as TdOptionProps[], keys) || {}); |
| 72 | + setValueToOption((prevValueToOption) => { |
| 73 | + const newValueToOption = getValueToOption(children as ReactElement, options as TdOptionProps[], keys) || {}; |
| 74 | + const { valueKey } = getKeyMapping(keys); |
| 75 | + const mergedValueToOption = { ...newValueToOption }; |
| 76 | + |
| 77 | + // 保持之前选中的 option 在映射中 |
| 78 | + // 避免远程搜索时,选中的 option 状态丢失 |
| 79 | + Object.keys(prevValueToOption).forEach((key) => { |
| 80 | + if (mergedValueToOption[key]) return; |
| 81 | + const isSelected = Array.isArray(value) |
| 82 | + ? value.some((v) => isValueSelected(v, key, valueType, valueKey)) |
| 83 | + : isValueSelected(value, key, valueType, valueKey); |
| 84 | + |
| 85 | + if (isSelected) { |
| 86 | + mergedValueToOption[key] = prevValueToOption[key]; |
| 87 | + } |
| 88 | + }); |
| 89 | + |
| 90 | + return mergedValueToOption; |
| 91 | + }); |
70 | 92 | // eslint-disable-next-line react-hooks/exhaustive-deps |
71 | | - }, [options, keys, children, reserveKeyword]); |
| 93 | + }, [options, keys, children, reserveKeyword, value, valueType]); |
72 | 94 |
|
73 | 95 | // 同步 value 对应的 options |
74 | 96 | useEffect(() => { |
|
0 commit comments