react-number-format 在插入值时显示格式

huangapple go评论128阅读模式
英文:

react-number-format Showing Format On inserting value

问题

react-number-format 在插入值时显示格式

我使用了这个包来进行电话号码输入格式化

```jsx
import { PatternFormat } from 'react-number-format';

<PatternFormat 
   value={value} 
   className='form-control'   
   format="(###) ###-####" 
/>

由于这个格式,每当我添加任何单个值时,格式化后的值会在值到达之前显示在输入框中。

react-number-format 在插入值时显示格式

我想在这个格式下显示值,但是当值到达时,当我只输入一个单个值时,它不应该显示那个 '-'。

我希望像下面这样:

react-number-format 在插入值时显示格式

这是我正在使用的npm包的链接:
https://s-yadav.github.io/react-number-format/docs/intro


<details>
<summary>英文:</summary>

react-number-format Showing Format On inserting value

I have used this package for the Phone Input format
  

    import { PatternFormat } from &#39;react-number-format&#39;;

    &lt;PatternFormat 
       value={value} 
       className=&#39;form-control&#39;   
       format=&quot;(###) ###-####&quot; 
     /&gt;

Due to this format whenever I add any single value, The formatted value show in the input. before the value reaches there. 

[![enter image description here](https://i.stack.imgur.com/q0kMG.png)](https://i.stack.imgur.com/q0kMG.png)

I want to show the value in This format but when the value reaches there, 
when I have entered only a single value it should not show that &#39;-&#39; there.

I want something like below
[![enter image description here][1]][1]

This is the link to the npm package I am using: 
https://s-yadav.github.io/react-number-format/docs/intro


  [1]: https://i.stack.imgur.com/En306.png

</details>


# 答案1
**得分**: 1

你可以根据值的长度来构建不同的模式,如果值达到了指定的长度,则将空格 ` ` 替换为破折号 `-`。

```javascript
import { PatternFormat } from 'react-number-format';

let pattern;
if (value.length >= 9) {
    pattern = "(###) ###-####";
} else {
    pattern = "(###) ### ####";
}

<PatternFormat 
   value={value} 
   className='form-control'   
   format={pattern} 
 />
英文:

You could build the pattern diffrent if the value reaches said length then change (empty space) for a - (dash)

import { PatternFormat } from &#39;react-number-format&#39;;

let pattern;
if (value.length &gt;= 9) {
    pattern = &quot;(###) ###-####&quot;;
} else {
    pattern = &quot;(###) ### ####&quot;;
}

&lt;PatternFormat 
   value={value} 
   className=&#39;form-control&#39;   
   format={pattern} 
 /&gt;

huangapple
  • 本文由 发表于 2023年6月2日 14:18:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76387595.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定