【问题标题】:React: Remove default value when user starts typingReact:当用户开始输入时删除默认值
【发布时间】:2020-05-20 20:33:14
【问题描述】:

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

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

到目前为止,这很好,如果我希望保留浮点数,我会努力。

value: 0 -> 用户输入 1 -> value: 1 -> 用户输入 . (浮点数)-> 值:1。-> 用户输入 0 -> 值 1

为了更好的说明,我整理了这个CodeSandbox

【问题讨论】:

    标签: javascript reactjs material-ui formik


    【解决方案1】:

    您的问题在于使用const newValue = Number(event.target.value);从字符串转换为数字

    由于11.0 在数字上是等价的,所以没有很好的方法来保存用户输入的 0 的确切数量。如果你想这样做,你可以考虑将其保留为字符串并仅转换当你想对它做一些数学运算时,回到一个数字。

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

    【讨论】:

      【解决方案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
            }}
          />
        );
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-12-30
        • 2012-09-07
        • 2011-02-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-20
        相关资源
        最近更新 更多