yaogengzhu / daily-share

个人博客记录、内容在issues
30 stars 4 forks source link

针对输入框的数字格式化(2022-8-25) #172

Open yaogengzhu opened 2 years ago

yaogengzhu commented 2 years ago

有一个小需求如下

image

输入框输入的同时,需要对数据处理格式化!

思路:结合正则处理数据

import React, { useMemo, useState } from "react";

const App = () => {
  const [value, setValue] = useState("");
  const newValue = useMemo(() => {
    const regx = /(?!^)(?=(\d{3})+$)/g;
    const result = value
      .replace(/^0+/, "")
      .replace(/,/g, "")
      .replace(regx, ","); // 123,456,789
    return result;
  }, [value]);

  return (
    <div>
      <input
        placeholder="请输入"
        value={newValue}
        onChange={(e) => {
          setValue(e.currentTarget.value);
        }}
      />
    </div>
  );
};
export default App;

效果 image