React Native OTP输入组件:TextInput光标未居中问题求助
React Native OTP输入组件光标偏右问题
我在React Native中构建了一个包含4个TextInput的OTP输入组件,但遇到光标未居中、轻微偏右的问题。已设置textAlign: 'center'但问题仍未解决。
相关代码
JSX部分
<View style={styles.otpContainer}> {[...new Array(4)].map((_, index) => ( <TextInput ref={ref => { inputs.current[index] = ref; }} style={[styles.otpInput, focusedIndex === index && { borderColor: tertiary }, emptyOtp && { borderColor: '#D00000' }, invalidOtp && { borderColor: '#D00000' }]} key={index} keyboardType="number-pad" maxLength={1} selectTextOnFocus contextMenuHidden testID={`OTPInput-${index}`} onChangeText={text => handleChangeText(text, index)} onKeyPress={e => handleKeyPress(e, index)} placeholder={focusedIndex !== index ? '•' : ''} onFocus={() => setFocusedIndex(index)} onBlur={() => setFocusedIndex(-1)} /> ))} </View>
样式部分
otpContainer: { flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: 8, marginTop: 40, textAlign: 'center', }, otpInput: { borderWidth: 1, borderColor: '#ccc', borderRadius: 8, paddingHorizontal: 16, textAlign: 'center', fontSize: 24, color: '#000', lineHeight: 55, width: 55, height: 55, }
已尝试的方法
- 移除padding并调整lineHeight
- 确保width、height与fontSize匹配
- 调整textAlign属性
解决建议
移除或调整paddingHorizontal
当前输入框宽度仅55,却设置了paddingHorizontal:16,左右内边距合计32,留给文本的空间被严重挤压,这是光标偏移的核心原因之一。可以直接移除paddingHorizontal,或者将输入框宽度调整为70以上,保证文本有足够居中空间。添加textAlignVertical: 'center'
部分平台(尤其是Android)需要显式设置垂直居中属性,避免字体渲染差异导致的光标偏移:otpInput: { // 其他样式保持不变 textAlignVertical: 'center', }移除selectTextOnFocus属性
该属性会在聚焦时自动选中文本,可能干扰光标默认居中逻辑,尝试移除后观察效果。微调字体与容器尺寸
尝试将fontSize调整为22,保持lineHeight和height完全一致(55),同时使用系统默认字体,避免自定义字体的字符宽度差异影响光标位置:otpInput: { fontSize: 22, fontFamily: Platform.OS === 'ios' ? 'System' : 'sans-serif', }平台特定样式优化
针对Android平台单独调整样式,解决跨平台渲染差异:import { Platform } from 'react-native'; otpInput: { // 通用样式 ...Platform.select({ android: { paddingHorizontal: 0, textAlignVertical: 'center', }, }), }
内容的提问来源于stack exchange,提问作者Arijit das
相关产品推荐
相关产品推荐

