Búsqueda de sitios web

Cómo navegar a una pantalla usando useNavigation() en React Native con TypeScript


Quería usar useNavigation para navegar a una pantalla. A continuación está mi código:

MainNav.tsx:

const defaultNavigationOptions: StackNavigationOptions = {
    ...
    ...
    ...
    headerRight: (props) => {
        return <AccountHeaderComponent tintColor={props.tintColor} />;
    },
    ...
    ...
    ...
};


const MainNavigator = () => {
return (
        <MainStack.Navigator>
            <MainStack.Screen
                name={"VerificationScreen}
                component={VerificationScreen}
            />
        </MainStack.Navigator>
    );
};

Esto creó un encabezado con un ícono de perfil como en la imagen de abajo.

cuando se haga clic en él, irá al componente AccountHeaderComponent

AccountHeaderComponent.tsx:

import AccountsPopUpComponent from "./AccountsPopUpComponent";

export interface AccountHeaderComponentProps {
    tintColor?: string,}

const AccountHeaderComponent = (props: AccountHeaderComponentProps) => {
    const {tintColor} = props;}
    return (<>
          <Modal>
              <AccountsPopUpComponent/>
          </Modal>
          <TouchableOpacity>
              <View>
                  <Icon name={'account-outline'}/>
              </View>
          </TouchableOpacity>
      </>
        </>
    )
};

Observe que aquí tengo un componente llamado AccountsPopUpComponent

AccountsPopUpComponent.tsx:

const AccountsPopUpComponent = (props: any) => {
    const {onClose} = props;

    const getCurrentPage = () => {
        switch (page) {
            case '':
                return <ProfileComponent />
            default:
                return <DummyComponent/>
        }
    }

    return (
          <View style={{flex: 1}}>{getCurrentPage()}</View>
    )
};

Finalmente tengo un ProfileComponent desde el cual quiero navegar a VerificationScreen, que está en el navegador principal.

ProfileComponent.tsx:

const ProfileComponent = (props: ProfileComponentProps) => {
  const navigation = useNavigation();

  const gotoVerifyScreen= () => {
    navigation.navigate(VerificationScreen);
  };

  return (
    <>
          <VerifyRibbonComponent
            gotoOTP={gotoVerifyScreen}
          />
    </>
  );
};

aquí en gotoVerifyScreen he usado useNavigation para ir a la pantalla de verificación, no me lleva a esa pantalla, pero si hago clic en el botón de retroceso de mi dispositivo entonces puedo ver esa pantalla. Este no es el tipo de funcionalidad que quería. Quiero ver esa pantalla cuando hago clic en VerifyRibbonComponent. He intentado mucho, pero no puedo encontrar el error que estoy cometiendo

Respuesta #1

Si estás usando un componente en el encabezado de una pila de navegación, deberías usar la navegación desde las props en lugar de useNavigation (no puedo encontrar la documentación sobre esto).

Intenta reemplazar const navigation=useNavigation(); con const navigation=props.navigation;

const defaultNavigationOptions: StackNavigationOptions = {
    ...
    ...
    ...
    headerRight: (props) => {
        return <AccountHeaderComponent 
           {...props} // <--- ADD THIS
           tintColor={props.tintColor} />;
    },
    ...
    ...
    ...
};
const AccountHeaderComponent = (props: AccountHeaderComponentProps) => {
    const {tintColor} = props;}
    return (<>
          <Modal>
              <AccountsPopUpComponent 
                {...props} // <--- ADD THIS
              />
          </Modal>
          <TouchableOpacity>
              <View>
                  <Icon name={'account-outline'}/>
              </View>
          </TouchableOpacity>
      </>
        </>
    )
};
const AccountsPopUpComponent = (props: any) => {
    const {onClose} = props;

    const getCurrentPage = () => {
        switch (page) {
            case '':
                return <ProfileComponent {...props} /> // <--- ADD THIS
            default:
                return <DummyComponent {...props} /> // <--- ADD THIS
        }
    }

    return (
          <View style={{flex: 1}}>{getCurrentPage()}</View>
    )
};
const ProfileComponent = (props: ProfileComponentProps) => {
  const gotoVerifyScreen= () => {
    props.navigation.navigate(VerificationScreen); // <--- CHANGE HERE
  };

  return (
    <>
          <VerifyRibbonComponent
            gotoOTP={gotoVerifyScreen}
          />
    </>
  );
};