LangInput.tsx 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import React, { useEffect } from "react";
  2. import { ListLangBySearchKey } from "@/api";
  3. import { useRequest } from "umi";
  4. import { AutoComplete } from "antd";
  5. interface LanItem {
  6. en: string;
  7. key: string;
  8. ["zh-CN"]: string;
  9. }
  10. export default function LangInput({
  11. value,
  12. onChange,
  13. }: {
  14. value: string;
  15. onChange: (value: any) => void;
  16. }) {
  17. const [lanOptions, setLanOptions] = React.useState<any[]>([]);
  18. const [formModel, setFormModel] = React.useState({
  19. langText: "",
  20. en: "",
  21. ["zh-CN"]: "",
  22. });
  23. const { run } = useRequest(ListLangBySearchKey, {
  24. manual: true,
  25. onSuccess(data, params) {
  26. setLanOptions(
  27. (data.result || []).map((item: LanItem) => ({
  28. ...item,
  29. label: `${item.en || ""}[zh-CN:${item["zh-CN"]}]`,
  30. value: item[params[0].searchLan],
  31. }))
  32. );
  33. },
  34. });
  35. const handleSearch = (serchKey: string, searchLan: "en" | "zh-CN") => {
  36. run({
  37. maxCount: 10,
  38. searchKey: serchKey,
  39. searchLan,
  40. });
  41. };
  42. const handleSelectLang = (option: LanItem) => {
  43. setFormModel(() => {
  44. return {
  45. ...formModel,
  46. langText: option.key,
  47. en: option?.en,
  48. ["zh-CN"]: option?.["zh-CN"],
  49. };
  50. });
  51. };
  52. const handleChange = (key: "en" | "zh-CN", val: string) => {
  53. setFormModel(() => {
  54. return {
  55. ...formModel,
  56. langText: "",
  57. [key]: val,
  58. };
  59. });
  60. };
  61. useEffect(() => {
  62. onChange(formModel);
  63. }, [formModel]);
  64. return (
  65. <div>
  66. <div>
  67. <AutoComplete
  68. allowClear
  69. placeholder="中文"
  70. options={lanOptions}
  71. onSearch={(val) => handleSearch(val, "zh-CN")}
  72. value={formModel["zh-CN"]}
  73. onChange={(val) => handleChange("zh-CN", val)}
  74. onSelect={(_val, opt) => handleSelectLang(opt)}
  75. />
  76. </div>
  77. <div>
  78. <AutoComplete
  79. allowClear
  80. style={{ width: "100%" }}
  81. placeholder="英文"
  82. options={lanOptions}
  83. onSearch={(val) => handleSearch(val, "en")}
  84. value={formModel.en}
  85. onChange={(val) => handleChange("en", val)}
  86. onSelect={(_val, opt) => handleSelectLang(opt)}
  87. />
  88. </div>
  89. </div>
  90. );
  91. }