Skip to content

Commit

Permalink
feat(menu): 支持配置字段别名
Browse files Browse the repository at this point in the history
  • Loading branch information
xiamiao committed Jun 12, 2024
1 parent 9416cd0 commit ac96bec
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
11 changes: 10 additions & 1 deletion packages/ui/menu/src/Menu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import { uuid } from '@hi-ui/use-id'
import { MenuDataItem, MenuFooterRenderProps } from './types'
import { MenuItem } from './MenuItem'
import MenuContext from './context'
import { getAncestorIds } from './util'
import { getAncestorIds, transformTreeData } from './util'

const MENU_PREFIX = getPrefixCls('menu')

Expand All @@ -41,6 +41,7 @@ export const Menu = forwardRef<HTMLDivElement | null, MenuProps>(
role = 'menu',
className,
data = NOOP_ARRAY,
fieldNames,
placement = 'vertical',
showCollapse = false,
// 仅对垂直模式有效
Expand Down Expand Up @@ -70,6 +71,10 @@ export const Menu = forwardRef<HTMLDivElement | null, MenuProps>(

const [activeParents, updateActiveParents] = useState(() => getAncestorIds(activeId, data))

data = useMemo(() => {
return transformTreeData(data, fieldNames)
}, [data, fieldNames])

useEffect(() => {
updateActiveParents(getAncestorIds(activeId, data))
}, [activeId, data])
Expand Down Expand Up @@ -303,6 +308,10 @@ export interface MenuProps extends Omit<HiBaseHTMLProps<'div'>, 'onClick'> {
* 菜单项数据列表
*/
data: MenuDataItem[]
/**
* 设置 data 中 id, title, disabled, children 对应的 key
*/
fieldNames?: Record<string, string>
/**
* 默认激活的菜单项 id
*/
Expand Down
33 changes: 33 additions & 0 deletions packages/ui/menu/src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,36 @@ export const filterTreeData = (
}) ?? []
)
}

export const transformTreeData = (
data: MenuDataItem[],
fieldNames: Record<string, string> | undefined
) => {
/**
* 转换对象
*/
const getKeyFields = (node: any, key: any) => {
if (fieldNames) {
return node[(fieldNames as any)[key] || key]
}
return node[key]
}

/**
* 递归处理树形数组
*/
const traverseNode = (node: MenuDataItem): MenuDataItem => {
const newNode: MenuDataItem = { ...node }
newNode.id = getKeyFields(newNode, 'id')
newNode.title = getKeyFields(newNode, 'title')
newNode.icon = getKeyFields(newNode, 'icon')
newNode.disabled = getKeyFields(newNode, 'disabled') ?? false
newNode.children = getKeyFields(newNode, 'children')
if (newNode.children) {
newNode.children = newNode.children.map(traverseNode)
}
return newNode
}

return data.map(traverseNode)
}

0 comments on commit ac96bec

Please sign in to comment.