gpt4 book ai didi

javascript - react native : How to make format card expiration with/using ?

转载 作者:数据小太阳 更新时间:2023-10-29 05:14:33 25 4
gpt4 key购买 nike

在 React Native 中使用 <TextInput/> ,我正在尝试制作 /仅在 <TextInput/> 时出现是焦点,如果输入另一个输入,它会留在那里。目前,格式是 MM/YY ,所以当用户键入第三个数字时,它将排在 / 之后。 , 如果用户按下返回键,它会删除 / 之前的数字。 .

那么实现前面提到的正确方法是什么?谢谢你,一定会接受答案。

我尝试了以下但长度出错,这只是添加了 /输入两位数字后:

  _changeCardExpiry(value) {
if (value.indexOf('.') >= 0 || value.length > 5) {
return;
}

if (value.length === 2 && this.state.cardExpiry.length === 1) {
value += '/'
}

//then update state cardExpiry
}

...

<TextInput
onChangeText={this._changeCardExpiry.bind(this)}
placeholder='MM/YY'
value={cardExpiry}
/>

最佳答案

在格式化中,您实际上需要 3 个函数,一个用于格式化实际值,第二个用于将格式化值转换回实际值,第三个用于检查到目前为止输入的输入是否有效。例如,对于日期输入,应忽略输入的字母输入,但同时应忽略 99,因为它不是一个月的有效输入。因此,对于您的特定情况,以下结构应该适合您(在此示例中 inputToValue 函数既检查输入的输入是否有效并根据它设置状态):

formatFunction(cardExpiry = ""){
//expiryDate will be in the format MMYY, so don't make it smart just format according to these requirements, if the input has less than 2 character return it otherwise append `/` character between 2nd and 3rd letter of the input.
if(cardExpiry.length < 2){
return cardExpiry;
}
else{
return cardExpiry.substr(0, 2) + "/" + (cardExpiry.substr(2) || "")
}
}

inputToValue(inputText){
//if the input has more than 5 characters don't set the state
if(inputText.length < 6){
const tokens = inputText.split("/");
// don't set the state if there is more than one "/" character in the given input
if(tokens.length < 3){
const month = Number(tokens[1]);
const year = Number(tokens[2]);
//don't set the state if the first two letter is not a valid month
if(month >= 1 && month <= 12){
let cardExpiry = month + "";
//I used lodash for padding the month and year with zero
if(month > 1 || tokens.length === 2){
// user entered 2 for the month so pad it automatically or entered "1/" convert it to 01 automatically
cardExpiry = _.padStart(month, 2, "0");
}
//disregard changes for invalid years
if(year > 1 && year <= 99){
cardExpiry += year;
}
this.setState({cardExpiry});
}
}
}
}

render(){
let {cardExpiry} = this.state;
return <TextInput
value = {this.formatFunction(cardExpiry)}
onChangeText={this.inputToValue.bind(this)}/>;
}

关于javascript - react native : How to make format card expiration with/using <TextInput/>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40313762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com