您可以使用正则表达式来实现此目的...其格式类似于 (555) 222-9999
onTextChange(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('');
this.setState({
phoneNum: number
});
return;
}
this.setState({
phoneNum: text
});
}
然后在
<TextInput>
...
<TextInput
onChangeText={(text) => this.onTextChange(text) }
value={this.state.phoneNum}
textContentType='telephoneNumber'
dataDetectorTypes='phoneNumber'
keyboardType='phone-pad'
maxLength={14}
/>
这是一个稍微复杂一些的解决方案,但它:
(55
或 5 位数字为 (555) 55
,或 6 位数字为 (555) 555-
)function formatPhoneNumber (text, previousText) {
if (!text) return text
const deleting = previousText && previousText.length > text.length
if (deleting) {
return text
}
let cleaned = text.replace(/\D/g, '') // remove non-digit characters
let match = null
if (cleaned.length > 0 && cleaned.length < 2) {
return `(${cleaned}`
} else if (cleaned.length == 3) {
return `(${cleaned}) `
} else if (cleaned.length > 3 && cleaned.length < 5) {
match = cleaned.match(/(\d{3})(\d{1,3})$/)
if (match) {
return `(${match[1]}) ${match[2]}`
}
} else if (cleaned.length == 6) {
match = cleaned.match(/(\d{3})(\d{3})$/)
if (match) {
return `(${match[1]}) ${match[2]}-`
}
} else if (cleaned.length > 6) {
match = cleaned.match(/(\d{3})(\d{3})(\d{4})$/)
if (match) {
return `(${match[1]}) ${match[2]}-${match[3]}`
}
}
return text
}