2 javascript css reactjs react-jsx react-native
在React Native中,我有两个<TextInput/>,一个接收MM / YY,另一个接收16位卡号。
在MM / YY的第一个输入中,我有:
<TextInput
onChangeText={this._handlingCardExpiry.bind(this)}
placeholder='MM/YY'
value={cardExpiry}
/>
Run Code Online (Sandbox Code Playgroud)
对于16位数字的卡号:
<TextInput
onChangeText={this._handlingCardNumber.bind(this)}
placeholder='0000 0000 0000 0000'
value={cardNumber}
/>
Run Code Online (Sandbox Code Playgroud)
为期满,我试图将它们拆分并存储为value属性${cardMonth}/${cardYear},但该文本甚至不这样,并且在卡号输入中每4位数字后添加空格会导致文本不会出现在输入中。
什么是使用<TextInput />的onChangeText和value属性处理以下内容的正确方法:
<TextInput/>,/在中间显示a ,输入的前两位数字将出现在之前,而后两位则出现在/后面。在此先感谢您,并会投票/接受答案。
您应该使用状态变量来更新TextInput值,以便每次文本更改时,都可以处理更改并更新状态,从而根据需要在组件中更新值。例如,尝试以下操作:
<TextInput
onChangeText={this._handlingCardExpiry.bind(this)}
placeholder='MM/YY'
keyboardType={'numeric'}
value={this.state.cardExpiry}
/>
Run Code Online (Sandbox Code Playgroud)
以上,我已经改变的值TextInput是this.state.cardExpiry。您可以对其他组件执行类似的操作。还要注意,我添加了keyboardType={'numeric'}它,实际上为用户提供了仅允许他们输入数字的键盘。下面,我将向您展示如何处理文本更改和更新状态。
_handlingCardExpiry(text) {
if (text.indexOf('.') >= 0 || text.length > 5) {
// Since the keyboard will have a decimal and we don't want
// to let the user use decimals, just exit if they add a decimal
// Also, we only want 'MM/YY' so if they try to add more than
// 5 characters, we want to exit as well
return;
}
if (text.length === 2 && this.state.cardExpiry.length === 1) {
// This is where the user has typed 2 numbers so far
// We can manually add a slash onto the end
// We check to make sure the current value was only 1 character
// long so that if they are backspacing, we don't add on the slash again
text += '/'
}
// Update the state, which in turns updates the value in the text field
this.setState({
cardExpiry: text
});
}
Run Code Online (Sandbox Code Playgroud)
您可以尝试此代码并对其进行调整以满足您的需求,但这是一般概念。您可以将类似的格式应用于您的16位字段,在此字段中,每4位在更新状态之前会添加一个空格。
我将添加处理卡号,因为它是原始问题的一部分:
_handlingCardNumber(number) {
this.setState({
cardNumber: number.replace(/\s?/g, '').replace(/(\d{4})/g, '$1 ').trim()
});
}
Run Code Online (Sandbox Code Playgroud)
哪里:
<TextInput
onChangeText={(text) => this._handlingCardNumber(text)}
placeholder='0000 0000 0000 0000'
value={this.state.cardNumber}
/>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1577 次 |
| 最近记录: |