如何在 React Native 应用程序中预填充 TextInput?

How to make TextInput prefill in React Native app?

我的 React Native 应用程序中有一个 TextInput 组件。并且我需要在该字段中预先填充408xx810xxx的掩码,字段中的1-3和6-8位数字,禁止为用户更改。有人可以推荐最好的方法吗?

          <TextInput
            style={[SS.input, styles.input]}
            placeholder={props.placeholder} placeholderTextColor={theme.inputPlaceholder}
            underlineColorAndroid='transparent' editable={!props.disabled}
            keyboardType={props.keyboardType || 'default'} autoCapitalize={capitalize}
            keyboardAppearance={props.keyboardAppearance}
            autoCorrect={autoCorrect} selection={state.position}
            secureTextEntry={this.state.guarded}
            value={this.state.value}
            onChangeText={this._onChangeText}
            onFocus={this._onFocus} onBlur={this._onBlur}
            autoFocus={props.autoFocus}
            multiline={props.multiline}
            maxLength={props.maxLength}
            onContentSizeChange={onContentSizeChange}
          />

对于预填充,您可以在构造函数中将硬编码的屏蔽值分配给状态 this.state.value

对于屏蔽,我建议您使用这个库:

https://github.com/react-native-community/react-native-text-input-mask

使用这个库屏蔽可以像这样工作

<TextInputMask
  refInput={ref => { this.input = ref }}
  onChangeText={(formatted, extracted) => {
  console.log(formatted) // +1 (123) 456-78-90
  console.log(extracted) // 1234567890
 }}
  mask={"+1 ([000]) [000] [00] [00]"}

/>

我创建了一个最小示例,它完全重现了您的用例,没有使用任何第三方库。

代码

更改文本:

changeText(text){
// we do not allow the deletion of any character
if (text.length >= 11){
  var tmp = text.split("")
  // check if there are still is a X value in string 
  const currentIndex = text.indexOf('X');
  if (currentIndex) {
    //if a X was found, replace it with the newest character
    tmp[currentIndex] = tmp[11];
    //remove latest character again
    tmp.pop();
  }
  this.setState({value: tmp.join("")})
  }
}

渲染:

  <View style={styles.container}>
     <TextInput
      value={this.state.value}
      onChangeText={(text) => this.changeText(text)}
     />
  </View>

工作演示

https://snack.expo.io/Sym-2W8RH

我发现使用 react-native-masked-text 库的最佳决定:

import { TextInputMask } from 'react-native-masked-text';
            <TextInputMask
              type='custom' 
              options={{mask: accountMask}} 
              maxLength={20}
              customTextInput={InputText} 
              customTextInputProps={this._loginMaskProps}
              value={vm.checkingAccount} keyboardType={'number-pad'}
              placeholder={accountPlaceholder} 
              onChangeText={vm.changeCheckingAccount}
            />

你只需要将 属性 输入 'custom',并根据 https://github.com/benhurott/react-native-masked-text 库创建一个掩码,在我的例子中是这样的:

 const accountMask = '40899810999999999999',