react native中TextInput作为数字框使用
warning:
这篇文章距离上次修改已过202天,其中的内容可能已经有所变动。
在React Native中,要创建一个只接受数字输入的TextInput组件,可以使用keyboardType
属性设置为numeric
来提供数字键盘,并使用onChangeText
属性来过滤非数字字符。以下是一个简单的示例:
import React, { useState } from 'react';
import { Text, TextInput, View } from 'react-native';
const NumericTextInput = () => {
const [value, setValue] = useState('');
const handleChangeText = (text) => {
const regex = /^[0-9]*$/;
if (regex.test(text)) {
setValue(text);
}
};
return (
<View>
<TextInput
keyboardType="numeric"
value={value}
onChangeText={handleChangeText}
style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
/>
</View>
);
};
export default NumericTextInput;
在这个例子中,handleChangeText
函数检查输入的文本是否只包含数字。如果是,则更新组件的状态;如果不是,则不进行更新,从而保证TextInput中只会显示数字。这样就创建了一个只接受数字输入的数字框。
评论已关闭