1

我提出这个问题是因为我最近在寻找 Mac 地址的字符串掩码。所以我决定创建自己的函数。以前的代码:

import React from 'react'
import {TextInput} from 'react-native-paper'
import {TextInputMask} from 'react-native-masked-text'
.
.
.
 <TextInput
            mode="outlined"
            label="MAC"

            render={props =>
                <TextInputMask
                    type={'custom'}
                    options={{
                        /**
                         * mask: (String | required | default '')
                         * the mask pattern
                         * 9 - accept digit.
                         * A - accept alpha.
                         * S - accept alphanumeric.
                         * * - accept all, EXCEPT white space.
                        */
                        mask: 'AA:AA:AA:AA:AA:AA'
                    }}
                    {...props}
                />

问题是当我慢慢输入 Mac 地址时,掩码会擦除文本,这种行为非常烦人。当我更快地键入 Mac 地址时它工作得很好,而这在常规使用流程中不会发生。Ps:我使用的是'react-native-masked-text'

4

1 回答 1

1

我的解决方案:

export function macAddressMask(input){
    const MAC_ADDRESS_WITH_MASK = 17
    const setCharacters = new Set(["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","A","B","C","D","E","F"])
    let res = ""
    let idxAtMask= -1
    for(let idx=0;idx<input.length;idx++){
        let currChar = input.charAt(idx)
        if(setCharacters.has(currChar)){
            if(idxAtMask===1){
                res+=":"
                idxAtMask = -1
            }
            res +=currChar
            idxAtMask++

        }
    }

    if(res.length <= MAC_ADDRESS_WITH_MASK){
        return res
    }else{
        return res.substr(0,MAC_ADDRESS_WITH_MASK)
    }
}

使用来自“react-native-paper”的 TextInput:

import {macAddressMask} from '../util/util-masks'
.
.
.
 <TextInput
            mode="outlined"
            label="MAC addresss"
            value={(parentState['macAddress'])}
            onChangeText={(text) => {
                setParentState('macAddress', macAddressMask(text))
            }}
        />
于 2020-06-24T18:48:21.807 回答