代码之家  ›  专栏  ›  技术社区  ›  Lucky_girl

我有一个文本输入,如何只启用小于9999.99的数字?

  •  0
  • Lucky_girl  · 技术社区  · 6 年前

    我有一个文本输入,怎么可能只允许数字低于9999.99?

       <TextInput
                        autoFocus
                        style={styles.inputStyle}
                        placeholder="0.00"
                        keyboardType="numeric"
                        maxLength={9}
                        autoCapitalize="none"
                        placeholderTextColor={Colors.white}
                        underlineColorAndroid={Colors.transparent}
                        value={billAmount}
                        onChangeText={this.handleTextChange}
                        selection={{start: cursor, end: cursor}}
                      />
    

    以下是handletextchange函数:

    handleTextChange = (text) => {
        const { cursor, billAmount } = this.state
        let newText
            newText = text.replace(/[^1-9]/g, '')
            this.setState({
              billAmount: newText
            })
    }
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   bennygenel    6 年前

    regex表达式也会删除任何点( . )中。这会导致你失去任何漂浮物。如果要启用浮动,则需要添加 是的。 给你的regex。

    然后,您只需要将文本解析为float,并检查它是否低于max float。

    样品

    handleTextChange = (text) => {
        const newAmount = parseFloat(text.replace(/[^1-9.]/g, ''));
        this.setState({
          billAmount: newAmount > 10000 ? '9999.99' : newAmount + ''
        });
      }
    
    推荐文章