假设我们有一个文本框(我将react与formik和material ui一起使用),它将接受价格(浮点数)。加载时,该字段的默认值为0。一旦用户手动输入一个数字,默认值就应该被清除,而手动输入的值应该取而代之。
值:0 ->用户输入1 ->值:1
到目前为止,这是很好的,我的困难是如果我想保留浮点数。
值:0 ->用户输入1 ->值:1 ->用户输入。(浮点) ->值: 1。->用户输入0 ->值1
为了更好地说明这一点,我把这个CodeSandbox放在一起。
发布于 2020-05-20 20:44:03
您的问题在于使用const newValue = Number(event.target.value);
将字符串转换为数字
因为1
和1.0
在数字上是等价的,所以没有很好的方法来保持用户输入的0的确切数量。如果您想这样做,您可以考虑将其保留为字符串,仅当您想对其进行一些数学运算时才将其转换回数字。
此外,由于您使用的是价格,因此您可以查看Number.toFixed()
,例如,总是在末尾放置两位小数。
发布于 2020-05-20 20:47:35
在这里,我编写了新的NuberFormField.js
组件:
import * as React from "react";
import { TextField } from "@material-ui/core";
import { useFormikContext } from "formik";
export const NumberFormField = ({
field,
form: { touched, errors },
inputProps,
...props
}) => {
const { setFieldValue, setFieldTouched } = useFormikContext();
field.onChange = event => {
const newValue = event.target.value; // This line is your bottleneck
setFieldValue(field.name, newValue);
setFieldTouched(field.name, true);
console.log("new val", newValue, field.name);
};
return (
<TextField
{...props}
inputProps={{
...inputProps,
type: "number"
}}
InputProps={{
...field,
...inputProps
}}
/>
);
};
https://stackoverflow.com/questions/61922392
复制