如何保持默认文本值不被删除 - React Native Text Input

问题描述 投票:0回答:2

我需要保留 +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"
      />

android react-native textinput iso
2个回答
2
投票

最后,我找到了这个问题的答案,而无需创建单独的标签前缀。

代码

        <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"
          />

0
投票

如果你想让用户无法删除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"
  />
© www.soinside.com 2019 - 2024. All rights reserved.