1

我想在drawer元素为clicked. 换句话说,我正在寻找一个与 property 等价的抽屉tabPress。我尝试将我的回调添加到属性focus。但是,只要相关堆栈中的“任何屏幕”处于“焦点”状态,就会执行此回调。

我希望代码只有在用户“点击” “抽屉项目”时才会被删除。这是可能吗?

import { createDrawerNavigator } from "@react-navigation/drawer";
const MyNav = createDrawerNavigator();

<MyNav.Navigator> 
  <MyNav.Screen name="abc" component={abcStack} 
    listeners={ ({ navigation, route }) => ({
        // This is executed whenever any screen in the stack is accessed. This does NOT satisfy my requirements. 
        focus: (e) => {
          console.log("We are in focus"); 
        }, 
        
        // Is there something like "tabPress" for Drawer stacks? 
        tabPress: (e) => {
          console.log("We are on tabPress"); 
        }, 
    })} 
  />
</MyNav.Navigator>

这个问题与 React-Navigation 版本 6 有关。

4

1 回答 1

0

我找到了一种解决方法,它应该在许多情况下都有效。这个想法是在抽屉被点击时向屏幕发送一个参数,抽屉正在调用该屏幕。如果抽屉调用堆栈,则必须将参数添加到堆栈的第一个屏幕

单屏抽屉式导航:

import { createDrawerNavigator } from "@react-navigation/drawer";
const MyNav = createDrawerNavigator();

<MyNav.Navigator> 
    <MyNav.Screen name="screen1" component={screen1} initialParams={{ opParam: "abc" }}/>
</MyNav.Navigator> 

带有堆栈的抽屉导航:

import { createDrawerNavigator } from "@react-navigation/drawer";
import { createNativeStackNavigator } from "@react-navigation/native-stack";

const stack1 = () => {
    const MyStack = createNativeStackNavigator();
    return (
    <MyStack.Navigator>
        <MyStack.Screen name="screen1" component={screen1}/>
    </MyStack.Navigator>
    );
}; 

const MyNav = createDrawerNavigator();

<MyNav.Navigator> 
    <MyNav.Screen name="stack1" component={stack1}/>
</MyNav.Navigator> 

屏幕一:

import React, { useEffect } from "react";
import { useIsFocused } from "@react-navigation/native";

const screen1 = (props) => {
 const isFocused = useIsFocused();

 useEffect(() => {      
    async function fetchData() {        
        // If this screen was loaded because of a click on the drawer, the following condition would be true.
        if (props.route?.params?.opParam === "abc") {
            // do whatever you want done when the user clicks on the drawer... 
            console.log("drawer was clicked"); 
        } 
    }
    
    // Only if this screen is in focus, we execute the function above.
    if (isFocused) {
        fetchData();
    }
 }, [ isFocused, props.route?.params?.opParam, ]); 

 return(
   // ............
 );
}; 
于 2022-03-06T02:05:20.387 回答