单击按钮反应本机控制选项卡导航

时间:2019-05-14 07:15:04

标签: react-native tabs react-navigation

单击按钮时如何移动到特定选项卡。我正在从API获取选项卡。所有标签仅包含一个带有不同数据的屏幕

1 个答案:

答案 0 :(得分:0)

如果您使用的是react-navigation,则可以使用

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

您可以详细了解here

下面是一个工作示例的代码。在底部,您会找到一个小吃的链接,该小吃显示了它的作用。

App.js

import React from 'react';
import AppContainer from './MainNavigation';
export default class App extends React.Component {
  constructor (props) {
    super(props);
    this.state = {
    };
  }

  render () {
    return (
      <AppContainer />
    );
  }
}

MainNavigation.js

import Screen1 from './Screen1';
import Screen2 from './Screen2';

import { createBottomTabNavigator, createAppContainer } from 'react-navigation';

// create TabNavigator
const screens = {
  Tab1: {
    screen: Screen1
  },
  Tab2: {
    screen: Screen2
  }
};

const config = {
  headerMode: 'none',
  initialRouteName: 'Tab1'
};


const TabNavigator = createBottomTabNavigator(screens, config);
export default createAppContainer(TabNavigator);

Screen1.js

import React from 'react';
import { View, StyleSheet, Text, Button } from 'react-native';

export default class Screen extends React.Component {

  onPress = () => {
    this.props.navigation.navigate('Tab2') // this will navigate to Tab2
  }

  render () {
    return (
      <View style={styles.container}>
        <Text>Tab 1</Text>
        <Button title={'Switch tab'} onPress={this.onPress} />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'white'
  }
});

Screen2.js

import React from 'react';
import { View, StyleSheet, Text, Button } from 'react-native';

export default class Screen extends React.Component {

  onPress = () => {
    this.props.navigation.navigate('Tab1') // this will navigate to Tab1
  }

  render () {
    return (
      <View style={styles.container}>
        <Text>Tab 2</Text>
        <Button title={'Switch tab'} onPress={this.onPress} />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'white'
  }
});

这是零食,所以您可以看到它的工作原理:

https://snack.expo.io/@andypandy/navigating-to-new-tab