【问题标题】:Bug in component input组件输入中的错误
【发布时间】:2020-07-03 05:09:31
【问题描述】:

我需要自定义 Ant Design 的 Input Number 字段。货币字段的格式为(货币) 例如:R $ 9.800,99。

我使用了 Intl,但 NaN 正在返回。如何解决此错误?

相关链接:

点击:Here

沙盒代码:https://codesandbox.io/s/friendly-hamilton-8pwvi

const MyInput = () => {
  const handleChange = event => {
    console.log(event);
  };

  return (
    <div>
      <InputNumber
        name="topText"
        style={{
          width: 400,
          marginRight: "1rem"
        }}
        formatter={value => new Intl.NumberFormat("pt-BR", {
            style: "currency",
            currency: "BRL"
          }).format(value)
        }
        onChange={handleChange}
      />
    </div>
  );
};

const App = () => {
  return (
    <div className="contain-all">
      <MyInput />
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById("root"));

【问题讨论】:

  • 您能否将您的代码发布为文本而不是图像?谢谢!
  • 看起来不错,好像传给这个组件的值是空的
  • 在操作前不需要将值解析为数字吗?
  • @norbitrial 我添加了沙盒链接。谢谢

标签: javascript html reactjs


【解决方案1】:

我查看了您的 ant 设计示例链接,我知道您也需要 parser。因此,我为您创建了一个工作代码示例。这是代码:

  <InputNumber
    name="topText"
    style={{
      width: 400,
      marginRight: "1rem"
    }}
    formatter={value => `R$ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ",")}
    parser={value => value.replace(/[R]\$\s?|(,*)/g, "")}
    onChange={handleChange}
  />

这是代码的工作示例https://codesandbox.io/s/weathered-morning-expib

由于它的数字类型字段,因此您可以使用箭头增加或减少值

【讨论】:

  • 首先我要感谢。但不幸的是,它对我不起作用。
  • 是的,我做到了。当使用键盘数字 NaN 出现在字段中
  • 似乎没有参加这种格式“R$ 9.800,99”。此外,我无法输入美分。
  • 我能够获得这种格式的 R$ 111.666,666。你能指定所有你想要的格式吗?
  • 我已根据您在上一条评论中发布的格式更新了正则表达式。查看代码框链接
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 2018-03-10
  • 2018-08-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多