目录
- 正文
- 实现原理
- 开源方案
正文
确认码控件也是一个较为常见的组件了,乍一看,貌似较难实现,但实则主要是障眼法。

实现原理
上图 CodeInput 组件的 UI 结构如下:
<View style={[styles.container]}>
<TextInput autoFocus={true} />
<View
style={[styles.cover, StyleSheet.absoluteFillObject]}
pointerEvents="none">
{cells.map((value: string, index: number) => (
<View style={[styles.cell]}>
<Text style={styles.text}>{value}</Text>
</View>
))}
</View>
</View>
TextInput 用于弹出键盘,接收用户输入,在它上面使用绝对定位覆盖了一个用于旁路显示的 View[style=cover]。
这就是 CodeInput 的实现原理了。
需要注意以下几个点:
- 设置
TextInput的autoFocus属性,控制进入页面时是否自动弹出键盘。 - 设置作为覆盖物的
View[style=cover]的pointerEvents属性为none,不接收触屏事件。这样当用户点击该区域时,底下的TextInput会获得焦点。 - 设置作为容器的
View[style=container]的高度,这个高度就是数字单元格的宽高。使用onLayout回调来获得容器的高度,用来设置数字单元格的宽高。
const { onLayout, height } = useLayout()
const size = height
return (
<View style={[styles.container, style]} onLayout={onLayout}>
<TextInput />
<View style={[styles.cover, StyleSheet.absoluteFillObject]}>
{cells.map((value: string, index: number) => (
<View
style={[
styles.cell,
{ width: size, height: size, marginLeft: index === 0 ? 0 : spacing }
]}>
<Text style={styles.text}>{value}</Text>
</View>
))}
</View>
</View>
)
cells是一个字符数组,用于存放数字单元格的文本内容,它的长度是固定的。它的内容由用户输入的值拆分组成,如果长度不够,则填充空字符串""。
export default function CodeInput({ value, length = 4 }) {
const cells = value.split('').concat(Array(length - value.length).fill(''))
}
开源方案
GitHub 上这个库实现了比较酷炫的效果。有需要的小伙伴可以使用。

这里有一个示例,供你参考。
以上就是React Native 中实现确认码组件示例详解的详细内容,更多关于React Native确认码组件的资料请关注其它相关文章!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

评论(0)