ColumnsTrans.jsx 2.31 KB
Newer Older
TZW's avatar
TZW committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
import { CopyOutlined } from '@ant-design/icons';
import { Input, Button, message, Divider } from 'antd';
import copy from 'copy-to-clipboard';
import { useState } from 'react';

const ColumnsTrans = () => {
  const [requestMsg, setrequestMsg] = useState('');
  const [newRequest, setnewRequest] = useState('');
  const [borderColor, setborderColor] = useState(null);

  const translateHandler = () => {
    try {
      let newString = JSON.parse(requestMsg);
      // let newString = eval('('+requestMsg+')');
      const newRequestArr = formatPrettier(newString);
      setnewRequest(newRequestArr);
      setborderColor('green');
    } catch (error) {
      message.error('“request”内容的格式不符合JSON字符串格式!');
      setborderColor('red');
    }
  };

  const formatPrettier = (jsonObj) => {
    // debugger
    // {
    //   title: '文本',
    //   key: 'text',
    //   dataIndex: 'id',
    // },
    let arr = [];
    for (let key in jsonObj) {
      if (key.toLowerCase() == 'id') continue;
      const newObj = {
        title: jsonObj[key],
        key: key,
        dataIndex: key,
      };
      arr = [...arr, newObj];
    }
    const newRequestString = JSON.stringify(arr)
      .replace(/\[/g, '[\n\t')
      .replace(/\]/g, ']')
      .replace(/\,/g, ',\n\t')
      .replace(/\{/g, '{\n\t')
      .replace(/\}\,/g, '\n\t},')
      .replace(/\}\]/g, '\n\t}\n]');
    return newRequestString;
  };

  return (
    <div>
      <Divider orientation="left">Request</Divider>
      <Input.TextArea
        name="text"
        placeholder="请输入Request内容,须符合JSON字符串格式"
        allowClear={true}
        value={requestMsg}
        autoSize={{ minRows: 10 }}
        onChange={(value) => {
          let newValue = value?.target?.value;
          setrequestMsg(newValue);
        }}
        style={{ borderColor: borderColor }}
      />
      <Button type="primary" onClick={translateHandler} style={{ margin: 6 }}>
        转换
      </Button>
      <Input.TextArea name="beautify" autoSize={{ minRows: 8, maxRows: 16 }} value={newRequest} />
      <Button
        style={{ margin: 6 }}
        onClick={() => {
          copy(newRequest);
          message.success('已成功复制到剪切板!');
        }}
      >
        复制
      </Button>
    </div>
  );
};

export default ColumnsTrans;