reactjs - 导航到屏幕时无法聚焦 TextInput
问题描述
我有一个 react-native-paper TextInput,我想在导航到屏幕时自动聚焦(使用 react-native-navigation)。我已经尝试autoFocus={true}
在 TextInput 上进行设置,但没有奏效。
在另一次尝试中,我尝试通过收听屏幕上的“焦点”事件来手动对焦,但这只是在我第一次打开屏幕时才对焦。有没有办法让它可靠地工作?
export default function NewAccountScreen({ navigation }) {
const [name, setName] = useState('');
const textInputRef = createRef();
// This isn't working, neither is autoFocus...
const focusOnInput = () => {
textInputRef.current?.focus();
}
navigation.addListener("focus", focusOnInput);
return (
<View>
<TextInput ref={textInputRef} label="Account name" value={name} onChangeText={setName}/>
</View>
)
}
解决方案
使用React.useRef()
而不是 createRef();
use React.useEffect
to listenref
被定义为可以使用它。
export default function NewAccountScreen({ navigation }) {
const [name, setName] = useState('');
const textInputRef = React.useRef();
React.useEffect(() => {
if(textInputRef.current){
const unsubscribe = navigation.addListener('focus', () => {
textInputRef.current?.focus()
});
return unsubscribe;
}
}, [navigation, textInputRef.current]);
return (
<View>
<TextInput ref={textInputRef} label="Account name" value={name} onChangeText={setName}/>
</View>
)
}
更新:如@pta2002 评论
我试过这个,它现在有时会聚焦,但有时它似乎聚焦然后立即失焦......
我测试了零食,正如他所说,它在某些时候已经不起作用了!
真的我不明白为什么?但我尝试了一些东西,它是工作。
听不听transitionEnd
_focus
试试这里的小吃
React.useEffect(() => {
if (textInputRef.current) {
const unsubscribe = navigation.addListener('transitionEnd', () => {
textInputRef.current?.focus();
})
return unsubscribe;
}
}, [navigation, textInputRef.current])
其他解决方案适用于我textInputRef.current?.focus();
的 setTimeout 和 1000 ms
React.useEffect(() => {
if (textInputRef.current) {
const unsubscribe = navigation.addListener('focus', () => {
setTimeout(() => {
textInputRef.current?.focus();
}, 1000);
})
return unsubscribe;
}
}, [navigation, textInputRef.current])
推荐阅读
- angular - 在 Angular 中获取字节流时,下载链接未定义
- sql - 如何在 SQL Server 中将字符串转换为日期?
- python - 使用 timeit + exec 的奇怪行为
- android - 尝试创建应用程序包时出现 FileUsesReservedNameException
- javascript - 拆分多个字符的问题
- c# - 来自服务器的 Unity json 数据返回 null
- c# - Windows 服务访问拒绝路径 192.168.1.XX
- c++ - 链表的复制构造函数导致内存错误
- php - Doctrine - 查询字段日期比较
- javascript - ESlint autofix 有可能破坏我的代码吗?