我需要保留 +65 作为默认值,用户无法从 TextInput 中删除 +65,并且用户可以根据需要输入他们的手机号码(另请参阅屏幕截图)。
我正在使用 TextInput 组件
const [phoneNumberText, setPhoneNumberText] = useState('+65');
<TextInput
keyboardType="numeric"
value={phoneNumberText}
onChangeText={(text) => {
const newPhone = text.replace(/^0+/, '');
setPhoneNumber(newPhone.replace(/ /g, '').replace('+', ''));
setPhoneNumberText(newPhone);
}}
autoFocus
style={styles.inputBg}
underlineColor="#f277c6"
theme={{
colors: {
placeholder: '#B2B4B8',
text: '#394452',
primary: '#f277c6',
underlineColor: '#f277c6',
},
}}
returnKeyType="done"
/>
最后,我找到了这个问题的答案,而无需创建单独的标签前缀。
代码
<TextInput
keyboardType="numeric"
value={phoneNumberText}
onChangeText={(text) => {
if (text.startsWith('+65')) {
const newPhone = text.replace(/^0+/, '');
setPhoneNumber(newPhone.replace(/ /g, '').replace('+', ''));
setPhoneNumberText(newPhone);
}
}}
autoFocus
style={styles.inputBg}
underlineColor="#f277c6"
theme={{
colors: {
placeholder: '#B2B4B8',
text: '#394452',
primary: '#f277c6',
underlineColor: '#f277c6',
},
}}
returnKeyType="done"
/>
如果你想让用户无法删除TextInput中手机的第一个值,那么试试这个:
const [phoneNumberText, setPhoneNumberText] = useState('+65');
<TextInput
keyboardType="numeric"
value={phoneNumberText}
onChangeText={(text) => {
if(text.length < 4 ){
text=phoneNumberText
}
const newPhone = text.replace(/^0+/, '');
setPhoneNumber(newPhone.replace(/ /g, '').replace('+', ''));
setPhoneNumberText(newPhone);
}}
autoFocus
style={styles.inputBg}
underlineColor="#f277c6"
theme={{
colors: {
placeholder: '#B2B4B8',
text: '#394452',
primary: '#f277c6',
underlineColor: '#f277c6',
},
}}
returnKeyType="done"
/>