如下所示,設(shè)置keyboardType='numeric',用戶輸入時(shí)就會(huì)彈出數(shù)字鍵盤,如果用戶通過粘貼或者其他方式輸入非數(shù)字時(shí),通過正則表達(dá)式把非數(shù)字替換成空字符串text.replace(/[^\d]+/, ''),達(dá)到只能輸入數(shù)字的目的。
代碼如下:
<TextInput
style={{height: 40, borderColor: 'gray', borderWidth: 1}}
onChangeText={(text) => {
const newText = text.replace(/[^\d]+/, '');
this.setState({inputValue: newText})
}}
value={this.state.inputValue}
keyboardType='numeric'
/>
————————2018-7-27更新分割線————————
評論區(qū)有程序猿反映在iOS上無效,我寫了個(gè)實(shí)例測試。下面貼出完整代碼及效果圖,供大家學(xué)習(xí)。
-
效果圖:
效果圖.gif
- 完整代碼(新建一個(gè)文件,全部粘貼即可):
import React, { Component } from 'react';
import {
View,
TextInput,
} from 'react-native';
export default class Demo extends Component {
constructor(props) {
super(props);
this.state = {
inputValue: "",
}
}
render() {
return (
<View>
<TextInput
style={{height: 40, borderColor: 'gray', borderWidth: 1}}
onChangeText={(text) => {
const newText = text.replace(/[^\d]+/, '');
//可以打印看看是否過濾掉了非數(shù)字
console.log(newText)
this.setState({inputValue: newText})
}}
value={this.state.inputValue}
//為了方便測試時(shí)輸入字母,屬性(keyboardType)不設(shè)置,實(shí)際使用時(shí)加上
// keyboardType='numeric'
/>
</View>
)
}
}
- 設(shè)備信息和版本號
測試手機(jī):iPhone 6 (真機(jī),而不是模擬器)
react-native:0.51.0
注:如果沒有達(dá)到效果,可以嘗試換個(gè)環(huán)境,換真機(jī)測試,或者更換react-native版本。
