简体   繁体   中英

Navigating to another Screen when a button is tapped in React Native

I'm quite new to React Native, I want to open another screen when a button is tapped, the screen that I want to show is already created. I have used TouchableOpacity as my button and used navigation on " onPress " prop. My app is already using Stack navigator and Tab navigator so I have installed those packages.

I have tried but I'm getting an error " undefined is not an object (evaluating 'navigation.navigate') "

Please help.

In the screen where I'm showing the button:

const myWebview = ({ navigation }) => {
  return (
      <View style={styles.buttonContainer}>
        <TouchableOpacity
          style={styles.button}
          onPress={() => navigation.navigate("NewListingScreen")}
        >
          <Text style={{ color: "#ffffff", fontWeight: "bold" }}>
            My Button Title
          </Text>
        </TouchableOpacity>
      </View>
  );
};

On my Tab Navigator (The screen works fine):

<Tab.Screen
        name={routes.newListingScreen}
        component={NewListingScreen}
        options={({ navigation }) => ({
          tabBarButton: () => (
            <NewListingButton
              onPress={() => {
                navigation.navigate(routes.newListingScreen);
                dispatch({
                  type: "SET_NEW_LISTING_SCREEN",
                  newListingScreen: true,
                });
              }}
            />
          ),
          tabBarVisible: !user,
        })}
      />

在此处输入图像描述

When I use const navigation = useNavigation();

I get this error: 在此处输入图像描述

My first guess is that the navigation object itself is undefined here. Navigation prop is only available on screens. -

const myWebview = ({ navigation }) => {

Using hooks is a better alternative to passing navigation objects to child components.

import { useNavigation } from '@react-navigation/native';

function NotificationsScreen() {
const navigation = useNavigation(); 
return(
 ...
  <TouchableOpacity
     style={styles.button}
     onPress={() => navigation.navigate('NewListingScreen')}
  >
 ...
);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM