React-navigation focus on input blurs immediately when going back to previous screen

这一生的挚爱 提交于 2020-06-27 03:41:24

问题


I want to focus on a textinput when I navigate to a new screen. This works when I add a screen to the stack, but not when I go back in the stack.

Instead, the input focuses for a second and blurs immediately.

Here is what I get:

  • Screen A is first in the stack and input blurs immediately
  • Screen B is added to the stack and works as intended

Any idea what is causing this?

FYI, I have the same issue if I use autoFocus.

Here is the whole (pretty straight forward) code:

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;

来源:https://stackoverflow.com/questions/61056722/react-navigation-focus-on-input-blurs-immediately-when-going-back-to-previous-sc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!