代码之家  ›  专栏  ›  技术社区  ›  Junius L.

TextInput只允许数字

  •  1
  • Junius L.  · 技术社区  · 6 年前

    我在用 TextInput

    handleInputChange = (text) => {
    
      if (/^\d+$/.test(text) || text === '') {
        this.setState({
          text: text
        });
      }
    }
    

    我的渲染方法

    render = () => {
      return (
        <View style={{
          flex: 0,
          flexDirection: 'row',
            alignItems: 'flex-end',
            marginTop: 50
        }}>
          <View style={{ flex: 0, marginLeft: 10 }}>
            <Text style={{ fontSize: 20}}>$</Text>
          </View>
          <View style={{flex: 1,}}>
            <TextInput
              onChangeText={this.handleInputChange}
              value={this.state.text}
              underlineColorAndroid='transparent'
              autoCorrect={false}
              spellCheck={false}
              style={{ paddingLeft: 5, fontSize: 20 }} />
          </View>
        </View>
      );
    }
    

    enter image description here

    2 回复  |  直到 6 年前
        1
  •  3
  •   mdaniel    6 年前

    请试试这个:

    1. keyboardType='numeric' 在标签中 TextInput
    2. 当你证明没有把数字放在电脑的键盘上时,请使用仿真器的键盘
    3. textContentType='telephoneNumber'
        2
  •  2
  •   Junius L.    6 年前

    正如拉维·鲁帕雷利亚所说,这是一只虫子 TextInput 当状态文本短于当前文本输入值时,不更新。好像这个问题已经解决了 react-native 0.57.RC . 目前我正在使用以下修复程序。

    handleInputChange = (text) => {
    
        const filteredText = text.replace(/\D/gm, '');
    
        if(filteredText !== text) {
          // set state text to the current TextInput value, to trigger
          // TextInput update.
          this.setState({ text: text });
    
          // buys us some time until the above setState finish execution
          setTimeout(() => {
    
            this.setState((previousState) => {
              return {
                ...previousState,
                text: previousState.text.replace(/\D/gm, '')
              };
            });
    
          }, 0);
        } else {
          this.setState({ text: filteredText });
        }
    }
    

    enter image description here

        3
  •  0
  •   Vishal Dhanotiya    5 年前

    React native未提供键盘类型,可从键盘中删除标点符号。您需要使用带replace方法的正则表达式从文本和集合中删除标点符号 keyboardType = 'numeric' .

    正则表达式

    /[-#*,.<gt;{}[]/]/gi

     onTextChanged(value) {
        // code to remove non-numeric characters from text
        this.setState({ number: value.replace(/[- #*;,.<>\{\}\[\]\\\/]/gi, '') });
      }
    

    请查看零食链接

    https://snack.expo.io/@vishal7008/1e004c

        4
  •  0
  •   Ronald Araújo    5 年前

    <TextInput 
       ...
       textContentType='telephoneNumber' 
       dataDetectorTypes='phoneNumber' 
       keyboardType='phone-pad'
    />
    
        5
  •  0
  •   Bhupesh Kumar    4 年前

    当有来自用户的输入时,你可以像这样改变特定文本输入框的键盘类型,如数字或字母等。。。

    <TextInput>
      //contains some code
      keyboardType="Numeric"
    </TextInput>