React Native Keychain自动填充失效,需再次点击TextInput才生效
问题原因
这个是iOS 15+ 搭配 Expo 43 对应 React Native 0.64 版本的已知兼容性问题:iCloud 钥匙串选中凭证后,原生输入框已经完成赋值,但没有触发 React Native 层的 onChangeText 事件,也没有同步更新 RN 侧绑定的状态值,只有输入框重新聚焦时才会触发状态同步,所以会出现延迟填充的现象。
可行解决方案
方案1:升级Expo版本(优先推荐)
Expo 44 及以上版本配套的 React Native 已经修复了该事件触发缺陷,直接将项目的 expo 依赖升级到 44.0.0 及以上版本即可解决问题,不需要修改业务代码。
方案2:低版本兼容处理(无法升级依赖时使用)
通过手动监听键盘收起事件,主动读取原生输入框的值更新状态,实现即时填充:
- 给两个输入框绑定 ref,监听键盘收起事件,同步原生值到状态:
import { useState, useRef, useEffect } from 'react'; import { Keyboard, TextInput } from 'react-native'; // 组件内逻辑 const LoginScreen = () => { const emailRef = useRef(null); const passwordRef = useRef(null); const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); useEffect(() => { const hideListener = Keyboard.addListener('keyboardDidHide', () => { // 钥匙串填充完成后键盘会自动收起,此时主动拉取原生输入框的值更新状态 if(emailRef.current?.value) setEmail(emailRef.current.value); if(passwordRef.current?.value) setPassword(passwordRef.current.value); }); return () => hideListener.remove(); }, []); return ( <> <TextInput ref={emailRef} textContentType='username' autoComplete="username" autoCorrect={false} value={email} onChangeText={(input) => setEmail(input)} /> <TextInput ref={passwordRef} autoComplete="password" textContentType='password' secureTextEntry={true} value={password} onChangeText={(input) => setPassword(input)} /> </> ) }
- 可选优化:将原有
autoComplete={true}替换为对应类型的枚举值,进一步提升iOS系统识别填充的准确性。
内容的提问来源于stack exchange,提问作者Alex H
相关产品推荐
相关产品推荐

