我正在尝试使用react-native-navigation v2构建一个动态向导。 我说动态是因为步数可能会有所不同,具体取决于用户选择的选项。
我想使用嵌套堆栈,所以我的应用程序的布局看起来像这样:
{
root: {
sideMenu: {
left: {/*...*/},
center: {
stack: {
children: [component1, /*...,*/ componentX]
}
}
}
}
}
ComponentX是我启动向导的地方,所以我推送一个新的堆栈,如下所示:
{
// ...
stack: {
children: [
component1,
//...,
componentX,
{
stack: {
children: [step1, step2, /*...,*/ stepN]
}
}
]
}
}
在用户在stepN上做出最后一个选择之后,我想用摘要屏幕替换嵌套堆栈,使其具有以下内容:
{
//...
stack: {
children: [
component1,
//...,
componentX,
summaryScreen
]
}
}
我可以使用Navigation.setRoot
重置整个事情,但这意味着我可能不得不将导航存储在Redux中。我也试过使用Navigation.setStackRoot
,但我的印象是它设置了父堆栈根而不是我的嵌套堆栈......
我终于设法解决了这个问题。 这是如何做:
const sideMenu = {
left: { /*...*/ },
center: {
stack: {
id: 'main', // this line is important
children: [/*...*/]
}
},
};
Navigation.setRoot({
root: { sideMenu },
});
Navigation.push(componentId, {
stack: {
id: 'wizard',
children: [
{
component: { /*...*/ },
},
],
}
})
wizard
上的屏幕Navigation.setStackRoot('wizard', [
{
component: { /*...*/ },
},
]);
Navigation.pop('main');
编辑:单独使用此方法,如果在嵌套屏幕上单击后退箭头,它将仅关闭整个嵌套堆栈而不是此屏幕。 我不得不使用自定义后退按钮,如下所示:
我通过使用自定义后退按钮解决了它:1。当我想要覆盖按钮的新屏幕时,使用选项
import Icon from 'react-native-vector-icons/MaterialIcons';
/* ... */
const backIcon = await Icon.getImageSource('arrow-back', 24, '#000');
const component = {
id: screenID,
name: screenID,
passProps,
options: {
topBar: {
leftButtons: [
{
id: 'backButton',
icon: backIcon,
},
],
},
}
};
return Navigation.push(componentId, { component });
import React, { Component } from 'react';
import { Navigation } from 'react-native-navigation';
const getDisplayName = WrappedComponent => WrappedComponent.displayName || WrappedComponent.name || 'Component';
export default function withCustomBackButton(WrappedComponent) {
class WithCustomBackButton extends Component {
componentDidMount() {
this.navigationEventListener = Navigation.events().bindComponent(this);
}
componentWillUnmount() {
if (this.navigationEventListener) this.navigationEventListener.remove();
}
navigationButtonPressed() {
// Your custom action
const { componentId } = this.props;
Navigation.pop(componentId);
}
render() {
return <WrappedComponent {...this.props} />;
}
}
WithCustomBackButton.displayName = `WithCustomBackButton(${getDisplayName(WrappedComponent)})`;
return WithCustomBackButton;
}
import withCustomBackButton from '../components/hoc/WithCustomBackButton';
/* ... */
Navigation.registerComponent('selectLocation', () => withCustomBackButton(SelectLocation));