OGeek|极客世界-中国程序员成长平台

标题: ios - 如何在另一个 React 组件中正确使用 TabNavigator [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 04:25
标题: ios - 如何在另一个 React 组件中正确使用 TabNavigator

问题 - 如何在另一个充当包装器组件的 React 组件中正确使用 React Navigation 的 TabNavigator 容器组件?

我想要实现的目标 - 基本上我希望 appbar 和 tabbar 都显示 - appbar 在顶部,tabbar (TabBarTop) 就在它下面,这是一种非常常见的设计模式。

我尝试了几种方法。

方法#1(嵌套在 StackNavigator 中)

Tab.js

export const Tab = TabNavigator({
    Tab1: { screen: Tab1Container },
    Tab2: { screen: Tab2Container }
  }, {
    tabBarComponent: TapBarTop,
    tabBarPosition: 'top'
  });

AppBar.js

class AppBarComponent extends Component {
  static navigationOptions = { header: null }
  render() {
    return (
      <View>
        *some more views, buttons blah blah here
      </View>
    )
  }
}
export default AppBarComponent;

我在 StackNavigator 中使用它们,比如

export default StackNavigator({
  stack1: { screen: AppBarComponent },
  stack2: { screen: Tab }
});

这导致在给定时间仅显示 1 个堆栈,这正是它的工作原理。而且我与 initialRouteName 没有任何关系。

方法#2(包装在另一个组件中)

<View style={{ flex: 1 }}>
  <AppBarComponent />
  <Tab />
</View>

这相反显示两个组件,但 this.props.navigation.navigate('somepath')push()pop()replace() 在内部和 .但是 this.props.navigation 及其方法都可以在这些组件中使用。

PS - 我正在使用 React Navigation v1 并在 iOS 上运行



Best Answer-推荐答案


方法一的解决方案

拥有一个只有一个屏幕的 StackNavigator,并在该屏幕中显示您的 TabNavigator。然后自定义header使用您的自定义 AppBarComponent

header

React Element or a function that given HeaderProps returns a React Element, to display as a header. Setting to null hides header.

示例

export default StackNavigator({
  stack: { 
    screen: Tab,
    navigationOptions: {
      header: (HeaderProps) => (<AppBarComponent headerProps={HeaderProps} />)
    }
  }
});

方法2的解决方案

您可以使用 withNavigation 包装不属于堆栈的组件HOC。

withNavigation is a higher order component which passes the navigation prop into a wrapped Component. It's useful when you cannot pass the navigation prop into the component directly, or don't want to pass it in case of a deeply nested child.

示例

class AppBarComponent extends Component {
  static navigationOptions = { header: null }
  render() {
    return (
      <View>
        *some more views, buttons blah blah here
      </View>
    )
  }
}
export default withNavigation(AppBarComponent);

关于ios - 如何在另一个 React 组件中正确使用 TabNavigator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50926323/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4