[英]In React Native Navigation, how do I send props to my screens?
I want to be able to use navigation on a different screen other than just the first one but I am getting an error that this.props does not exist.我希望能够在不同的屏幕上使用导航,而不仅仅是第一个屏幕,但我收到一个错误,提示 this.props 不存在。
I have my App.js file setup like this:我的 App.js 文件设置如下:
import { createStackNavigator } from '@react-navigation/stack';
import { NavigationContainer } from '@react-navigation/native';
import Screen2 from './screens/Screen2';
import Screen3 from './screens/Screen3';
import HomeScreen from './screens/HomeScreen';
const Stack = createStackNavigator();
function HomeScreen({ navigation }) {
return (
<View>
<Button
title="Go to Screen2"
onPress={() => {
navigation.navigate('Screen2');
}}
/>
<Button
title="Go to Screen3"
onPress={() => {
navigation.navigate('Screen3');
}}
/>
</View>
);
const App: () => React$Node = () => {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Screen2" component={Screen2} />
<Stack.Screen name="Screen3" component={Screen3} />
</Stack.Navigator>
</NavigationContainer>
);
};
The buttons in app.js work but if I go to Screen2 and click a button that intends to go to another (Screen3 in the example below), props does not exist. app.js 中的按钮可以工作,但是如果我转到 Screen2 并单击一个打算转到另一个按钮(下面示例中的 Screen3),则道具不存在。
Example Screen2.js would look like this:示例 Screen2.js 将如下所示:
const Screen2: () => React$Node = () => {
return (
<>
<View style={{ flex: 1 }}>
<Button
title="Go to Screen3"
onPress={goToScreen3}}
/>
</View>
</>
);
function goToScreen3() {
if(condition){
this.props.navigate.navigate('Screen3');
}}
How do I pass the props so that I can use navigation in my second screen?如何传递道具以便我可以在第二个屏幕中使用导航?
In Functional Component there is no this binding so you need to get the props from the function first在 Functional Component 中没有 this 绑定,所以你需要先从函数中获取 props
check th检查日
const Screen2 = (props) => {
return (
<>
<View style={{ flex: 1 }}>
<Button
title="Go to Screen3"
onPress={goToScreen3}}
/>
</View>
</>
);
function goToScreen3() {
if(condition){
props.navigate.navigate('Screen3');
}
}
}
For functional component sometimes it's tricky to pass navigation through props as well.对于功能组件,有时通过 props 传递导航也很棘手。 So just use withNavigation.
所以只需使用withNavigation。
you have to import it and wrap the function with it.你必须导入它并用它包装函数。
import { withNavigation } from 'react-navigation';
const Screen2 = props => {
const goToScreen3 = () => {
if(condition){
props.navigate.navigate('Screen3');
}}
return (
<>
<View style={{ flex: 1 }}>
<Button
title="Go to Screen3"
onPress={goToScreen3()}
/>
</View>
</>
);
export default withNavigation(Screen2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.