You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

React自定义数字输入框无法输入逗号和句号的问题求助

Solution to Allow Comma and Period in Number Input for Formatted Values

Hey there! I see you want to input formatted numbers like 3,456.78 with commas as thousand separators and periods for decimals. Let's adjust your code to make this work smoothly—here's how:

Key Issues to Fix

Right now, two main parts are holding you back:

  • The convertStringToNumber function can't handle commas (using Number(val) directly will return NaN for inputs with commas)
  • The convertNumberToString function just outputs a plain number string, not the formatted version you want

Modified Code with Explanations

Let's update the relevant parts of your component and conversion functions:

import React, { useState, useRef, useEffect } from "react";
import "./styles.css";

export interface NumberFieldInterface {
  convertStringToNumber?: (value: string) => number;
  convertNumberToString?: (value: number) => string;
  onChange?: (value: number) => void;
  value: number;
}

const NumberField = React.forwardRef<HTMLInputElement, NumberFieldInterface>(
  (props, ref) => {
    const { value, onChange, convertStringToNumber, convertNumberToString } = props;
    const inputRef = useRef(null);
    let convertedValue;

    const onValueChange = (value: string) => {
      if (typeof onChange === "function" && convertStringToNumber) {
        convertedValue = convertStringToNumber(value);
        const isNumber = typeof convertedValue === "number" && isFinite(convertedValue);
        if (isNumber) {
          onChange(convertedValue);
        }
      }
    };

    return (
      <div>
        <input
          type="text"
          ref={ref}
          value={convertNumberToString?.(value)}
          onChange={(e: React.FormEvent<HTMLInputElement>) => {
            onValueChange(e.currentTarget.value);
          }}
          // Optional: Restrict to valid characters only
          pattern="[0-9.,]*"
        />
      </div>
    );
  }
);

export default function App() {
  const [inputValue, setInputValue] = useState<number>(0);
  const ref = useRef(null);

  const handleChange = (val: number) => {
    setInputValue(val);
  };

  return (
    <div className="App">
      <NumberField
        ref={ref}
        convertStringToNumber={(val) => {
          // Strip commas first, then convert to number
          const cleanedValue = val.replace(/,/g, "");
          return Number(cleanedValue) || 0; // Fallback to 0 if conversion fails
        }}
        convertNumberToString={(val) => {
          // Auto-format number with thousand separators
          return new Intl.NumberFormat('en-US').format(val);
        }}
        value={inputValue}
        onChange={handleChange}
      />
    </div>
  );
}

What Changed?

  1. convertStringToNumber:

    • We first remove all commas from the input string using val.replace(/,/g, "") to avoid NaN during conversion
    • Added a fallback to 0 in case the input is completely invalid (like empty or non-numeric text)
  2. convertNumberToString:

    • Used Intl.NumberFormat('en-US') to automatically format numbers with thousand separators—this will turn 3456.78 into 3,456.78 for display
  3. Optional Input Restriction:

    • Added a pattern="[0-9.,]*" attribute to the input to guide users away from typing invalid characters (like letters), though the conversion function will handle invalid inputs regardless

Now you can type commas and periods in the input, and it will correctly convert to a numeric value while displaying the formatted version you need!

内容的提问来源于stack exchange,提问作者Judoboy Alex

火山引擎 最新活动