如何使用react-native将textinput格式化为电话号码

时间:2019-11-11 23:10:13

标签: react-native numbers

用户键入电话号码时,我希望该号码以电话号码格式显示,例如(123)456-7890

我不确定该怎么做,但这是我目前拥有的代码。

使用UseState:

const [PNumber,setPNumber] = useState();

在我的TextInput中:

<TextInput
  style={Fonts.Inp}
  keyboardType={'number-pad'}
  placeholder="(604) 333-3333"
  placeholderTextColor='gray'
  maxLength={10}
  onChangeText = {(Text)=> setPNumber(Text)}
/>

因此,当前显示为“ 1234567890”。 我希望显示为(123)456-7890

1 个答案:

答案 0 :(得分:0)

尝试一下

_onChangeText = (text) => {
  let formatedNo = this.formatMobileNumber(text);
  this.setState({ phone: formatedNo });
};

formatMobileNumber=(text=> {
  var cleaned = ("" + text).replace(/\D/g, "");
  var match = cleaned.match(/^(1|)?(\d{3})(\d{3})(\d{4})$/);
  if (match) {
    var intlCode = match[1] ? "+1 " : "",
      number = [intlCode, "(", match[2], ") ", match[3], "-", match[4]].join(
        ""
      );
    return number;
  }
  return text;
}

...
<TextInput       
    maxLength={maxLength}
    keyboardType={keyboardType}
    onChangeText={text => {
       this._onChangeText(text);
    }}
    placeholder={placeholder}
    placeholderTextColor={Constants.APP_TEXT_GRAY_COLOR}
    value={value}
 />
...