簡體   English   中英

只讀輸入的千位分隔符

[英]Thousand separator for read-only input

我想在 ReadOnly 輸入類型編號中實現一千個空格分隔符,但是當嘗試這樣做時,它似乎不起作用,我只能寫三個數字,然后整個事情就消失了。

代碼

<input
  type="number"
  onChange={props.onInputChange}
  value={props.value ? props.value : 0}
  min={props.min}
  max={props.max}
  readOnly="readonly"
 />
export const priceFormatterSpace = (price) => {
  return price.toString().replace(/\B(?=(\d{3})+(?!\d))/g, " ");
};

我該怎么做?

這應該可以解決問題。 您必須將輸入更改為type="text"並首先刪除非數字字符然后格式化數字。 您在type="number"的輸入字段中只能有一組有限的字符。 Chrome 只允許每個值使用一個句點或逗號。

export default function App() {
  const [value, setValue] = useState("");

  // Format value by the thousands. Add a comma between
  const numberWithCommas = (num) => {
    return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  }
 
  // Remove non-numeric characters from input
  const removeNonNumeric = (num) => {
    return num.toString().replace(/[^0-9]/g, "");
  }

  // Handle user typing into the input 
  const handleChange = (e) => {
    const inputValue = numberWithCommas(removeNonNumeric(e.target.value))

    setValue(inputValue);
  };

  return (
    <input type="text" onChange={handleChange} value={value} />
  );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM