簡體   English   中英

React Native:如何在 React Navigation 中傳遞 props

[英]React Native: How to pass props in React Navigation

在我的 React Native 應用程序中,我使用的是react-navigation並且有一個使用react-native-webview的類組件:

<WebView source={{ uri: this.props.url }} />

這是在 StackNavigator 中實現的,如下所示:

<Stack.Navigator>
  <Stack.Screen name="Viewer" component={WebViewScreen} />
</Stack.Navigator>

如何使用React Contexturl prop 傳遞給WebViewScreen組件?

查看react-navigation docs ,它提到了一個替代方案:

<Stack.Screen name="Home">
  {props => <HomeScreen {...props} extraData={someData} />}
</Stack.Screen>

但有警告,所以我想嘗試使用上下文。 理想情況下,我將能夠推送到堆棧並將WebViewScreen指向任何 url:

this.props.navigation.push('Viewer', {
    route: 'https://www.example.com'
})

如果您只關心將導航操作上的值更改為您的 Webview 所在的屏幕,您可以簡單地通過route屬性訪問您在導航中傳遞的數據:

const route = this.props.route.params?.route ?? 'default url';

<WebView source={{ uri: route }} />

來源: https : //reactnavigation.org/docs/upgrading-from-4.x/#no-more-getparam

添加提供程序並獲取組件中的值。

const MyContext = React.createContext();

<MyContext.Provider value={{url: '/somethig'}}>
  <Stack.Navigator>
    <Stack.Screen name="Viewer" component={WebViewScreen} />
  </Stack.Navigator>
</MyContext.Provider>

在您的主HomeScreen使用鈎子來獲取您的價值:

const value = useContext(MyContext);

暫無
暫無

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

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