簡體   English   中英

React-navigation:如何根據條件設置screen的initialParams?

[英]React-navigation: How to set initialParams for screen based on condition?

我有BottomTabsNavigator作為StackNavigator的一部分。

當我啟動應用程序時,我需要根據BottomTabsNavigator中的條件在主頁選項卡中傳遞initialParams

顯然,BottomTabsNavigator 僅呈現一次,而 initialParams 始終根據條件發送默認值而不是新值。

  <Tab.Screen
    name="Home"
    component={HomeScreen}
    options={{
      title: 'Home',
      tabBarIcon: 'home-outline',
      tabBarLabel: 'Home',
    }}

    initialParams={{ 'tappedNotification1': notificationOpened }} // <---- here I want to send notificationOpened  value when its value is updated, 
  />

我使用下面的掛鈎將notificationOpened的值更新為 true(需要作為主屏幕的initialParams發送。

    function onOpened(openResult) {
      navigation.navigate('NotificationDetailsScreen', {
        ...openResult.notification.payload.additionalData,
        tappedNotification: true,
        isRead: false,
      });

      setNotificationOpened(true);
    }
    OneSignal.addEventListener('opened', onOpened);

    return () => {
      OneSignal.removeEventListener('opened', onOpened);
    }; // unsubscribe on unmount
  }, [navigation, user]);

更新評論:

@Guruparan Giritharan 我根據你的建議做了完全相同的事情。 這有點難以解釋,但請留在我身邊。

在我的BottomTabsNavigator ,我聲明了一個 state 'notificationOpened' with intialValue false 並將其傳遞給NotificationContext.Provider值。 可在主頁中訪問。

Home屏幕有一個模態彈出窗口,應根據上下文的notificationOpened中收到的值(modal should display when notificationOpened is false)

在我的例子中,我將notificationOpened值從BottomTabsNavigator更新為 true,因此模式不會顯示。

但是Home在開始時從上下文中接收到false並顯示模態。 希望這是有道理的。

官方文檔建議使用上下文或類似 redux 的某種存儲來更新選項卡上的計數變量。 你有類似的要求。 您可以查看此示例以獲得執行此操作的想法。

首先,您需要創建一個上下文文件

const NotificationContext = React.createContext(0);

export default NotificationContext;

以及包含您的選項卡的文件

const MyTabs = () => {
  const [count, setCount] = React.useState(0);

  return (
    <NotificationContext.Provider value={count}>
      <View style={{ flex: 1 }}>
        <Text>{count}</Text>
        <Button title="count" onPress={() => setCount(count + 1)} />
        <Tab.Navigator>
          <Tab.Screen name="Home" component={HomeScreen} options={{ title: 'My home' }}/>
          <Tab.Screen name="Settings" component={SettingsScreen} options={{ title: 'My home 2' }}/>
        </Tab.Navigator>
      </View>
    </NotificationContext.Provider>
  );
};

主屏幕文件可以使用“usecontext”讀取和更新自身

import NotificationContext from './NotificationContext';

export function HomeScreen() {
  const count = React.useContext(NotificationContext);
  return (
    <View>
      <Text>{count}</Text>
    </View>
  );
}

此示例基於您提供的零食。 https://snack.expo.io/@guruparan/tabs-with-context

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM