当屏幕加载时,我使用以下代码将焦点放在:
useEffect(() => {
InteractionManager.runAfterInteractions(() => {
if (refText.current) {
refText.current.focus();
}
});
}, []);
这按预期工作。然而,在提交事件上,需要再次关注。
function myEvent() {
if (refText.current) {
refText.current.focus();
}
}
这不再关注文本。有什么想法吗?
最佳答案
实际上,我不知道为什么您需要在提交处理程序中使用 if
语句来将焦点设置在 TextInput
上,但无论如何,我认为您在您的 Button
声明中包含一个事件处理程序。例如:
function App() {
const textRef = useRef();
const handleSubmit = () => {
if (textRef.current) textRef.current.focus();
};
return (
<View>
<TextInput placeholder="Input" ref={textRef}/>
<Button title="Submit" onPress={handleSubmit} />
</View>
);
}
});
它工作正常,正如您在 Sandbox 中看到的那样.
关于android - 如何在事件发生后重新聚焦 <TextInput>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69377011/