如何制作货币转换组件

How to make a currency conversion component

我正在尝试创建一个具有两个字段的货币转换组件。两者都是可编辑的,因此您可以输入目标金额或起始金额。

我试过用react-number-format,效果很好,但是根据计算,小数点太多了,我想限制在2位:

我尝试使用 toFixed() 并尝试将其四舍五入,但根据我进入无限循环的计算,因为我的 handleChange 方法是这样的:

    // change amount to send
    const handleAmount = value => {
        setValues({
            ...values,
            amount: value,
            total: value * rates.rates[values.country]
        });
    };

    // change amount to receive
    const handleReceive = value => {
        setValues({
            ...values,
            total: value,
            amount: value / rates.rates[values.country]
        });
    };

我想实现的是这样的,不超过2位小数:

这里是 codesandbox,其中的代码没有按预期工作:https://codesandbox.io/s/zen-khorana-wks08

我怎样才能做到这一点?

提前致谢

所以我想出了解决方法。我无法使用 react-number-format 因为它更新了两个值,格式化它们并给我错误。

我使用 currency.js 来格式化数字,不包括我正在输入的字段上的小数点分隔符,使用户更容易输入值:

  const [values, setValues] = React.useState({
    field1: "",
    field2: ""
  });

  const rate = 12341941;

  const handleChange = (value, field) => {
    if (field === "field1") {
      setValues({
        field1: currency(value, { precision: 0 }).format(),
        field2: currency(value)
          .multiply(rate)
          .format()
      });
    }
    if (field === "field2") {
      setValues({
        field1: currency(value)
          .divide(rate)
          .format(),
        field2: currency(value, { precision: 0 }).format()
      });
    }
  };

这里是任何有同样问题的人的codesandbox:https://codesandbox.io/s/zen-khorana-wks08