首页 > 解决方案 > 例如,如果有人试图复制粘贴文本,我如何只允许数字输入做出反应

问题描述

我只想允许文本输入,不允许文本中的复制粘贴

我已经让数字键盘应该打开,但我只想在这个输入字段期间允许数字

<TextInput
         underlineColorAndroid='transparent'
         style={styles.TextInputStyle}
         placeholder='0.00'
         keyboardType={'numeric'}
         value={this.state.shippingCharge}
         onChangeText={(shippingCharge) => this.setState({ shippingCharge })}
     />

标签: javascriptreactjsreact-native

解决方案


尝试Regex对输入使用验证(例如最大长度为 100 个数字的数字):

<TextInput
     underlineColorAndroid='transparent'
     style={styles.TextInputStyle}
     placeholder='0.00'
     keyboardType={'numeric'}
     value={this.state.shippingCharge}
     onChangeText={this.onChangeTextInput}
 />



onChangeTextInput = (text) => {
    const numericRegex = /^([0-9]{1,100})+$/
    if(numericRegex.test(text)) {
        this.setState({ shippingCharge: text })
    }
}

推荐阅读