导航到新屏幕时,我想专注于文本输入。当我向堆栈中添加屏幕时,此方法有效,但是当我返回堆栈中时,此方法无效。
相反,输入会聚焦一秒钟并立即模糊。
这就是我得到的:
你知道是什么原因造成的吗?
仅供参考,如果我使用自动对焦,也会遇到同样的问题。
这是完整的代码(很简单):
import { NavigationContainer } from "@react-navigation/native";
import { createStackNavigator } from "@react-navigation/stack";
import * as React from "react";
import { TextInput, View, Button, Text } from "react-native";
function ScreenA({ navigation }) {
const textInputRef = React.useRef();
const focusOnInput = e => {
textInputRef.current.focus();
};
navigation.addListener("focus", focusOnInput);
return (
<View>
<Text>SCREEN A</Text>
<TextInput ref={textInputRef} />
<Button title="Go to screen B" onPress={() => navigation.navigate("ScreenB")} />
</View>
);
}
function ScreenB({ navigation }) {
const textInputRef = React.useRef();
const focusOnInput = e => {
textInputRef.current.focus();
};
navigation.addListener("focus", focusOnInput);
return (
<View>
<Text>SCREEN B</Text>
<TextInput ref={textInputRef} />
<Button title="Go to screen A" onPress={() => navigation.navigate("ScreenA")} />
</View>
);
}
const Stack = createStackNavigator();
function TestComp() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen component={ScreenA} name="ScreenA" />
<Stack.Screen component={ScreenB} name="ScreenB" />
</Stack.Navigator>
</NavigationContainer>
);
}
export default TestComp;