反应:在用户开始键入时删除默认值



假设我们有一个文本框(我正在使用带有formik和Material ui的反应(,它将接受价格(浮点数(。加载时,字段的默认值为 0。一旦用户手动输入数字,应清除默认值,并应取而代之的是手动输入的值。

值:0 -> 用户输入 1 -> 值:1

到目前为止还好,我挣扎的地方是如果我想保留浮点数。

值:0 -> 用户输入 1 -> 值:1 -> 用户输入 。(浮点( ->值:1。 ->用户输入 0 ->值 1

为了更好地说明它,我把这个CodeSandbox放在一起。

您的问题在于从字符串到数字的转换,并带有const newValue = Number(event.target.value);

由于11.0在数值上是等效的,因此没有好方法可以保留用户输入的确切 0 数。如果你想这样做,你可以考虑把它作为一个字符串,只有在你想对它做一些数学运算时才转换回一个数字。

此外,由于您正在使用价格,因此您可以查看Number.toFixed()例如始终在末尾放置 2 位小数。

在这里,我编写了您的新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
}}
/>
);
};

最新更新