使用类组件响应本机堆栈导航



我目前正在构建一个 react 本机应用程序,并使用堆栈导航器在我的应用程序中的屏幕之间导航。在我的应用程序中.js,我目前以以下格式存储屏幕:

const Stack = createStackNavigator();
export default function App() {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="screen1">
<Stack.Screen name="screen1" component={Screen1}></Stack.Screen>
<Stack.Screen name="screen2" component={Screen2}></Stack.Screen>
</Stack.Navigator>
</NavigationContainer>
);
}

用户进入屏幕 1 后,我希望能够通过按下按钮导航到屏幕 2。我通读了文档,只看到了有关如何使用功能组件执行此操作的示例,例如:

function Screen1({ navigation }) {
return (
<View>
<Button title="Go to Home" onPress={() => navigation.navigate('screen2')} />
</View>
);
}

但是我如何使用类组件来做到这一点:

class Screen1 extends Component {
render() {
return(
<View>
// This does not work because I do not know how to pass in the navigation object
<Button title="Go to Home" onPress={() => navigation.navigate('screen2')} />
</View>
)
}
}

我在哪里通过{ navigation }

你不必传递导航,它作为道具传递。

您可以像下面一样访问它

this.props.navigation.navigate('nextScreen')

1 :import { Link, withRouter } from 'react-router-dom';

2 :export default withRouter(Component);

Login = () => {
this.props.history.push("/login")
}

最新更新