本篇内容主要讲解“React Native中如何实现确认码组件”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“React Native中如何实现确认码组件”吧!
正文
确认码控件也是一个较为常见的组件了,乍一看,貌似较难实现,但实则主要是障眼法。

实现原理
上图 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>
)export default function CodeInput({ value, length = 4 }) {
const cells = value.split('').concat(Array(length - value.length).fill(''))
}到此,相信大家对“React Native中如何实现确认码组件”有了更深的了解,不妨来实际操作一番吧!这里是天达云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!