如何在本机中以这种“ xxx-xxx-xxxx”格式输入电话号码?

时间:2019-08-11 13:14:12

标签: react-native

我希望当我在TextInput字段中输入数字时,它将作为

123-456-7890format,而无需安装任何库。

1 个答案:

答案 0 :(得分:1)

您可以使用正则表达式转换数据。

示例

import React, { Component } from 'react';
import { TextInput,View } from 'react-native';

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = { num: '' };
  }

  changeNum(num) {
    formatNum = num.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3');
    this.setState({
      num: formatNum
    });
  }

  render() {
    return (
      <View style={{flex:1,justifyContent:"center",alignItems:"center"}}>
      <TextInput
        style={{height: 40, borderColor: 'gray', borderWidth: 1, width:"80%"}}
        onChangeText={(num) => this.changeNum(num)}
        value={this.state.num}
        maxLength={12} 
        keyboardType={'numeric'}
      />
      </View>
    );
  }
}