【问题标题】:React Number format does not allow to range validationReact Number 格式不允许范围验证
【发布时间】:2023-02-19 23:01:04
【问题描述】:

要求是我需要从用户那里获取重量输入,重量范围在 3 到 21 之间,对于最大限制我能够实现它,但是对于 0,1,2 我应该做什么。

      <Form.Group className="num-group">
                                              <NumberFormat
                                                className="form-control"
                                                allowNegative={false}
                                                value={Number(
                                                  comment.weight
                                                )}
                                                isAllowed={checkLength}
                                                onValueChange={(e) =>
                                                  handleValueChange(
                                                    e,
                                                    index,
                                                    "weight"
                                                  )
                                                }
                                              />
                                            </Form.Group>
  const checkLength = (inputObj) => {
    const { value, floatValue, formattedValue } = inputObj;
    console.log(inputObj);
    if (value <= 20) return true;

    return false;
  };
  const handleValueChange = (e, index, name) => {
    console.log(e.value);
    let result = Number(e.value.length) <= 2;

    if (result) {
      const tempData = [...data];
      tempData[index] = { ...tempData[index], [`${name}`]: Number(e.value) };
      setData(tempData);
    }
  };

我需要实现的是,假设用户要编辑字段,应该只取 3-21 个值之间的值。

目前,根据 onValueChange 函数,当我执行 Backspace 更改值时,预期结果变为零,但我只需要用户输入 3-21 个值。

如果写入逻辑值 >=3 && 值 <=20,在这种情况下它不允许我更改,因为它在 ONchange 上工作并且一次只取一个值。

例如,如果数字是 3,我需要将其设为 4,那么如果我编写范围逻辑,它将不允许我这样做。

因为它在我们首先编辑时变为零,然后我们将输入详细信息。

请建议我该怎么办?

【问题讨论】:

    标签: reactjs react-number-format


    【解决方案1】:
    const checkLength = (inputObj) => {
        const { value, floatValue, formattedValue } = inputObj;
        console.log(inputObj);
        if (value <= 20) return true;
    
        return false;
      };
    
    Here change your condition to:
    if (value <= 20 || value===undefined)
    

    【讨论】:

      猜你喜欢
      • 2019-04-18
      • 2017-03-25
      • 1970-01-01
      • 2014-05-11
      • 2015-11-07
      • 1970-01-01
      • 2019-12-09
      • 2013-12-30
      • 1970-01-01
      相关资源
      最近更新 更多