![](/img/trans.png)
[英]Pass navigation in props to menu element in React Native and React Navigation
[英]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 Context將url
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.