Punycode 在线转换

发表于: 2022-02-05
阅读预计: 1 分钟
文章字数: 138

互转工具:

源码:

import punycode from 'punycode';
import { useEffect, useState } from 'react';

export function Form() {
  const [unicode, setUnicode] = useState('');
  const [ascii, setAscii] = useState('');
  const [settingAscii, setSettingAscii] = useState(false);
  const [settingUnicode, setSettingUnicode] = useState(false);

  useEffect(() => {
    if (settingUnicode) {
      setAscii(punycode.toASCII(unicode));
      setSettingUnicode(false);
    }
  }, [unicode]);

  useEffect(() => {
    if (settingAscii) {
      try {
        setUnicode(punycode.toUnicode(ascii));
      } catch (e) {}
      setSettingAscii(false);
    }
  }, [ascii]);

  return (
    <div className='mx-auto my-4'>
      <div className='form-control'>
        <label className='label'>
          <span className='label-text'>Unicode</span>
        </label>
        <input
          type='text'
          placeholder='中文域名'
          value={unicode}
          onChange={(e) => {
            setSettingUnicode(true);
            setUnicode(e.target.value);
          }}
          className='input input-bordered text-secondary'
        />
      </div>

      <div className='form-control'>
        <label className='label'>
          <span className='label-text'>ASCII</span>
        </label>
        <input
          type='text'
          placeholder='Punycode 转码域名'
          value={ascii}
          onChange={(e) => {
            setSettingAscii(true);
            setAscii(e.target.value);
          }}
          className='input input-bordered text-secondary'
        />
      </div>
    </div>
  );