简体   繁体   English

ReactJS / Typescript / Redux - 带有数据类型编号和逗号值的 onChange 事件

[英]ReactJS / Typescript / Redux - onChange event with datatype number and comma values

the following situation: I have a reactjs/redux/typescript application.以下情况:我有一个 reactjs/redux/typescript 应用程序。

I have a two way binding with redux for my input textboxes with the onChange event.对于带有 onChange 事件的输入文本框,我有一个与 redux 的双向绑定。 The props are all declared with the datatype "number".道具都用数据类型“数字”声明。 Everything works as expected.一切都按预期工作。

The only problem i have is when i want to type in comma seperated values i cannot store it as number in my redux store.我唯一的问题是当我想输入逗号分隔值时,我无法将其作为数字存储在我的 redux 商店中。 It seems that it will store it as string and not as number but i want to store it as number.似乎它将它存储为字符串而不是数字,但我想将它存储为数字。

My input box looks like this:我的输入框是这样的:

<input
value={props.number || ""}
onChange={e => props.updateValue({ number: +e.target.value })}
/>

with the +e.target.value i convert the string value from the input field to a number, because i expect a number and nothing else.使用+e.target.value我将输入字段中的字符串值转换为数字,因为我只需要一个数字。 But i want also that ive been able to put in a comma seperated value.但我也希望我能够输入逗号分隔值。

The problem is that because of the onChange event the comma value cannot be stored because when i try to type in for example "1.1" on the second character "1."问题是由于 onChange 事件无法存储逗号值,因为当我尝试在第二个字符“1”上输入例如“1.1”时。 this is not a number.这不是一个数字。

For better understanding i created a codesandbox example:为了更好地理解,我创建了一个代码沙盒示例:

https://codesandbox.io/s/create-react-app-with-typescript-xt2tc?fontsize=14 https://codesandbox.io/s/create-react-app-with-typescript-xt2tc?fontsize=14

My question: What is the best/smartest way to handle this situation?我的问题:处理这种情况的最好/最聪明的方法是什么? I dont want to store the values as String, because it is not a string.我不想将值存储为字符串,因为它不是字符串。

Thanks in advance for your help and for all ideas.提前感谢您的帮助和所有想法。

Just set the <input type="number" /> , it's also better for UX and makes more sense semantically.只需设置<input type="number" /> ,它对 UX 也更好,并且在语义上更有意义。

  <input
    type="number"
    value={props.number || ""}
    onChange={e => props.updateValue({ number: +e.target.value })}
  />

Demo:https://codesandbox.io/s/create-react-app-with-typescript-bu305演示:https://codesandbox.io/s/create-react-app-with-typescript-bu305

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM