代码之家  ›  专栏  ›  技术社区  ›  Johan

如何让我的输入接受空值或数字?

  •  0
  • Johan  · 技术社区  · 3 年前

    我想做两个输入,一个用于 最小 值,一个用于 最大 价值

    我设法制作了一个可恢复的组件,并使其接受 min 和 max 值,但现在我无法删除数据以写入另一个。

    如果我删除该值, 0 已设置。

    如何接受空值或0到5之间的数字?

    谢谢

    const FilterAnnonceNombrePiece = () => {
      const [filtresMax, setFiltresMax] = useAtom(numberPiecesMax);
      const [filtresMin, setFiltresMin] = useAtom(numberPiecesMin);
    
      const minValue = 0;
      const maxValue = 5;
    
      const setNumberPiecesMin = (value: number | string) => {
        setFiltresMin(numberWithMinMaxDefaultValue(value, minValue, maxValue, minValue));
      };
    
      const setNumberPiecesMax = (value: number | string) => {
        setFiltresMax(numberWithMinMaxDefaultValue(value, minValue, maxValue, maxValue));
      };
    
      const numberWithMinMaxDefaultValue = (
        value: number | string,
        minValue: number,
        maxValue: number,
        defaultValue: number,
      ): number => {
    
      const res = typeof value === 'number' ? value : parseFloat(value);
      const emptyString = value === '';
    
        if (emptyString) {
          return defaultValue;
        }
    
        if (isNaN(res)) {
          return defaultValue;
        }
    
        if (res < minValue) {
          return minValue;
        }
    
        if (res > maxValue) {
          return maxValue;
        }
    
        return res;
    };
    
      return (
          <div className="hk-flex hk-flex-row hk-gap-1.5">
            <InputFloatingLabel
              label="min"
              value={filtresMin}
              onChange={setNumberPiecesMin}
              inputProps={{ type: 'text' }}
            />
            <InputFloatingLabel
              label="max"
              value={filtresMax}
              onChange={setNumberPiecesMax}
              inputProps={{ type: 'text' }}
            />
          </div>
      );
    };
    
    1 回复  |  直到 3 年前
        1
  •  0
  •   RubenSmn    3 年前

    对于这种类型的函数,我建议使用 guard clauses 。

    而不是返回 defaultValue 当值为空字符串时,可以返回空字符串。通过这种方式,您可以在不影响最小/最大逻辑的情况下更改输入中的值。由于这是一个受控输入,你实际上不能返回0/默认输入,因为这不允许,就像你说的擦除值一样

    const numberWithMinMaxDefaultValue = (
      value: number | string,
      minValue: number,
      maxValue: number,
      defaultValue: number
    ) => {
      // if empty return default value
      // if (value === "") return defaultValue;
      if (value === "") return "";
    
      // convert value of string to number / float
      if (typeof value === "string") {
        value = parseFloat(value);
      }
    
      // check for the thresholds
      if (value < minValue) return minValue;
      if (value > maxValue) return maxValue;
    
      // if no cases match the value is valid and we can return
      return value;
    };