Compound.tsx 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import { List, Select, Space, Typography } from "antd";
  2. import { useEffect, useState } from "react";
  3. import { get } from "../../request";
  4. import {
  5. IApiResponseDictList,
  6. IDictFirstMeaningResponse,
  7. IFirstMeaning,
  8. } from "../api/Dict";
  9. const { Text } = Typography;
  10. interface IOptions {
  11. value: string;
  12. label: string;
  13. }
  14. interface IWidget {
  15. word?: string;
  16. add?: string;
  17. split?: string;
  18. }
  19. const Widget = ({ word, add, split }: IWidget) => {
  20. const [compound, setCompound] = useState<IOptions[]>([]);
  21. const [factors, setFactors] = useState<IOptions[]>([]);
  22. const [meaningData, setMeaningData] = useState<IFirstMeaning[]>();
  23. const [currValue, setCurrValue] = useState<string>();
  24. const onSelectChange = (value: string) => {
  25. console.log("selected", value);
  26. get<IDictFirstMeaningResponse>(
  27. `/v2/dict-meaning?lang=zh-Hans&word=` + value.replaceAll("+", "-")
  28. ).then((json) => {
  29. if (json.ok) {
  30. setMeaningData(json.data);
  31. }
  32. });
  33. };
  34. useEffect(() => {
  35. if (typeof add === "undefined") {
  36. setFactors(compound);
  37. } else {
  38. setFactors([{ value: add, label: add }, ...compound]);
  39. setCurrValue(add);
  40. onSelectChange(add);
  41. }
  42. }, [add, compound]);
  43. useEffect(() => {
  44. get<IApiResponseDictList>(`/v2/userdict?view=compound&word=${word}`).then(
  45. (json) => {
  46. if (json.ok) {
  47. const data = json.data.rows.map((item) => {
  48. return { value: item.factors, label: item.factors };
  49. });
  50. setCompound(data);
  51. }
  52. }
  53. );
  54. }, [word]);
  55. return (
  56. <div>
  57. <Select
  58. value={currValue}
  59. style={{ width: "100%" }}
  60. onChange={onSelectChange}
  61. options={factors}
  62. />
  63. <List
  64. size="small"
  65. dataSource={meaningData}
  66. renderItem={(item) => (
  67. <List.Item>
  68. <div>
  69. <Text strong>{item.word}</Text>{" "}
  70. <Text type="secondary">{item.meaning}</Text>
  71. </div>
  72. </List.Item>
  73. )}
  74. />
  75. </div>
  76. );
  77. };
  78. export default Widget;