1

Пытаюсь настроить числовое поле инпута (InputNumber https://ant.design/components/input-number/) так, чтобы в него не вводились никакие символы и буквы, кроме цифр. Стандартное поведение инпута в библиотеке Ant Design (https://ant.design/): буквы вводятся, а при клике вне поля, все буквы пропадают и поле остаётся пустым. Встроенных пропсов у либы, отвечающих за поведение ввода в инпут не нашёл. Прошу помочь разобраться, вот изначальный мой код:

import React from "react";
import { observer } from "mobx-react";
import { NumberInput } from "components/uui/NumberInput/NumberInput";
import { BaseModel } from "models/BaseModel";
import classNames from "classnames";
import styles from "components/fields/styles.less";

interface Props {
  name: string;
  model: BaseModel;
  onChange?: (value: number) => void;
  autoFocus?: boolean;
  size?: "large" | "small";
  min?: number;
  className?: string;
  noLabel?: boolean;
  labelColor?: string;
  max?: number;
}

@observer
export class NumberField extends React.Component<Props> {
  static defaultProps = {
    min: 5,
    autoFocus: true,
    labelColor: "darkGray"
  };

  private handleInput = (value: number): void => {
    const { model, name, onChange } = this.props;
    model.setAttribute(name, value);

    if (onChange) {
      onChange(value);
    }
  };

  get value(): number {
    const { model, name } = this.props;

    // @ts-ignore
    // TODO: make it generic
    return model[name];
  }

  render(): React.ReactChild {
    const { className, model, noLabel, name, labelColor, ...rest } = this.props;

    return (
      <div className={classNames(styles.formField, className)}>
        {!noLabel && (
          <label className={styles[labelColor]}>{model.getLabel(name)}</label>
        )}
        <NumberInput value={this.value} onChange={this.handleInput} {...rest} />
      </div>
    );
  }
}

По идее мне просто нужно не принимать никакие символы кроме цифр, в значении value, но мои варианты почему-то не работают. Если я правильно понимаю, то мне нужно написать в одну из этих функций проверку на число или replace:

private handleInput = (value: number): void => {
    const { model, name, onChange } = this.props;        
    model.setAttribute(name, value);

    if (onChange) {
      onChange(value);
    }
  };

  get value(): number {
    const { model, name } = this.props;

    // @ts-ignore
    // TODO: make it generic
    return model[name];
  } 

Перепробовал кучу вариантов и ничего не работает...=(

2 ответа 2

0

В случае контролируемого инпута в обработчике события handleInput можно использовать обновлённое value в котором останутся только цифры:

const clearedValue = value.replace(/\D/g,'');
0
const InputNumber = React.forwardRef((ref, props) => {
   const { initialValue, onChange = null } = props;
   const [currentValue, setCurrentValue] = useState(initialValue);

   const handleChange = useCallback((event) => {
      const value = event.target.value.replace(/\D+/g, '');

      if (currentValue !== value) {
         setCurrentValue(value);
         
         if (onChange !== null) {
            onChange(event);
         }
      }

   }, [currentValue, onChange]);

   return (
      <Input
         {...props}
         ref={ref}
         onChange={onChange}
         value={currentValue}
      />
   );
});

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.