UiLangSelect.tsx 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { Button, Dropdown } from "antd";
  2. import type { MenuProps } from "antd";
  3. import { useMemo, useState } from "react";
  4. import { set, get } from "../../locales";
  5. import { GlobalOutlined } from "@ant-design/icons";
  6. interface IUiLang {
  7. key: string;
  8. label: string;
  9. }
  10. const uiLang: IUiLang[] = [
  11. { key: "en-US", label: "English" },
  12. { key: "zh-Hans", label: "简体中文" },
  13. { key: "zh-Hant", label: "繁体中文" },
  14. ];
  15. const UiLangSelect = () => {
  16. /**
  17. * ✅ 初始值直接计算
  18. */
  19. const [curr, setCurr] = useState(() => {
  20. const currLang = get();
  21. return uiLang.find((i) => i.key === currLang)?.label;
  22. });
  23. /**
  24. * ✅ antd menu items 必须 useMemo + 正确类型
  25. */
  26. const items: MenuProps["items"] = useMemo(
  27. () =>
  28. uiLang.map((lang) => ({
  29. key: lang.key,
  30. label: lang.label,
  31. })),
  32. []
  33. );
  34. /**
  35. * ✅ 点击逻辑
  36. */
  37. const onClick: MenuProps["onClick"] = ({ key }) => {
  38. set(key as string); // ← 只传一个参数
  39. const label = uiLang.find((i) => i.key === key)?.label;
  40. setCurr(label);
  41. location.reload();
  42. };
  43. return (
  44. <Dropdown menu={{ items, onClick }} placement="bottomRight">
  45. <Button type="text" icon={<GlobalOutlined />}>
  46. {curr}
  47. </Button>
  48. </Dropdown>
  49. );
  50. };
  51. export default UiLangSelect;