React Native验证码输入组件首次渲染自动唤起键盘方案咨询
实现react-native-confirmation-code-field渲染后自动唤起键盘并聚焦第一个单元格
我正在使用react-native-confirmation-code-field包,希望在屏幕渲染完成后立即唤起键盘,且让第一个输入单元格获得焦点。以下是我的代码:
export default function ConfirmationCode({ route, navigation }) { const [value, setValue] = useState("") const ref = useBlurOnFulfill({ value, cellCount: CELL_COUNT }) const [props, getCellOnLayoutHandler] = useClearByFocusCell({value, setValue}) return ( <CodeField ref={ref} {...props} value={value} onChangeText={setValue} cellCount={CELL_COUNT} rootStyle={styles.codeFieldRoot} keyboardType="number-pad" textContentType="oneTimeCode" renderCell={({ index, symbol, isFocused }) => ( <Text key={index} style={[styles.cell, isFocused && styles.focusCell]}> {symbol || (isFocused ? <Cursor /> : null)} </Text> ) } /> ) }
实现方案
借助useEffect和组件ref主动触发聚焦
组件挂载完成后,通过useEffect钩子调用CodeField实例的focus方法,直接让第一个输入单元格获得焦点,同时唤起键盘。react-native-confirmation-code-field的CodeField组件原生支持focus方法,可直接调用。修改后的完整代码
在原代码中添加useEffect逻辑:
import { useEffect, useState } from 'react'; // 保持其他导入不变 export default function ConfirmationCode({ route, navigation }) { const [value, setValue] = useState("") const ref = useBlurOnFulfill({ value, cellCount: CELL_COUNT }) const [props, getCellOnLayoutHandler] = useClearByFocusCell({value, setValue}) useEffect(() => { // 组件挂载后立即聚焦第一个单元格 ref.current?.focus(); }, []); return ( <CodeField ref={ref} {...props} value={value} onChangeText={setValue} cellCount={CELL_COUNT} rootStyle={styles.codeFieldRoot} keyboardType="number-pad" textContentType="oneTimeCode" renderCell={({ index, symbol, isFocused }) => ( <Text key={index} style={[styles.cell, isFocused && styles.focusCell]}> {symbol || (isFocused ? <Cursor /> : null)} </Text> ) } /> ) }
- 注意事项
- 使用可选链操作符
?.是为了避免组件未完全挂载时调用focus方法导致报错。 - 如果
CELL_COUNT是动态变化的值,需要将其添加到useEffect的依赖数组中,确保数值变更时能重新触发聚焦逻辑。 - 部分iOS/Android系统可能限制应用自动唤起键盘,这种情况下该逻辑可能失效,需要用户手动点击输入框,但大部分常规场景下上述代码可以正常工作。
- 使用可选链操作符
内容的提问来源于stack exchange,提问作者Andrew Einhorn
相关产品推荐
相关产品推荐

