简体   繁体   中英

How to set the initial tab from outside

Consider the scenes below:

<Scene key='home' component={HomeComponent} hideNavBar title={'home'}/>
<Scene key="myTabBar" tabs={true} hideNavBar tabBarStyle={style.tabBarStyle}>
    <Scene 
        key="myTab" 
        title="My Tab" 
        icon={MyTabIcon} 
        component={MyTabComponent} hideNavBar />
    <Scene 
        key="myTab_1" 
        title="My Tab 1" 
        icon={MyTabIcon} 
        component={MyTabComponent1} hideNavBar />
</Scene>

I have two buttons in HomeComponent, Button1 and button Button2.

I want to show myTab_1 when Button1 clicked, and show myTab_2 when Button2 clicked. How can i achieve this?

Actually its quite simple, but there is no documentation or issue discussed. To evaluate this, we can look at the source code of TabBar in repo src directory.

... (imports)

class TabBar extends Component {

  ...

  static onSelect(el) {
    if (!Actions[el.props.name]) {
      throw new Error(
        `No action is defined for name=${el.props.name} ` +
        `actions: ${JSON.stringify(Object.keys(Actions))}`);
    }
    if (typeof el.props.onPress === 'function') {
      el.props.onPress();
    } else {
      Actions[el.props.name]();
    }
  }
}

When we click on the tab itself, we actually invoke the function onSelect (take a look at render part) which simply routes using Action[tabbarbutton.props.name]()

For your code its Action.myTab_1() in your TouchableOpacity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM