StackNavigator中嵌套的TabNavigator:控制标题

问题描述 投票:6回答:5

我的设置很像这样:

let Tabs = createBottomTabNavigator({
    screen1: Screen1,
    screen2: Screen2
})

let Stack = createStackNavigator({
    tabs: Tabs
    otherScreen: OtherScreen
})

堆栈导航器有一个标题,没关系。我想要的是获取不同的标题图标取决于我目前在哪个标签上。

我使用以下版本:

"react": "16.3.1",
"react-native": "~0.55.2",
"react-navigation": "^2.2.5"

我考虑过切换我的设置,以便每个标签屏幕都有自己的StackNavigator,但我喜欢切换标签时有滑动动画,我不希望标题图标滑动。标题栏应保持静态,但根据当前标签显示不同的图标。

reactjs react-native react-navigation
5个回答
6
投票

你可以像下面这样使用https://reactnavigation.org/docs/en/stack-navigator.html

//Screen1 Stack.

const Screen1 = createStackNavigator ({
    Home: {
        screen: Home,
        navigationOptions: {
            header: null //Need to set header as null.
        }
    }
});

//Screen2 Stack

const Screen2 = createStackNavigator ({
    Profile: {
        screen: Profile,
        navigationOptions: {
            header: null  //Need to set header as null.
        }
    }
});


let Tabs = createMaterialTopTabNavigator({
    Screen1:{
      screen: Screen1 //Calling Screen1 Stack.
    },
    Screen2:{
      screen: Screen2 //Calling Screen2 Stack.
    }
},{ tabBarPosition: 'bottom' }) //this will set the TabBar at Bottom of your screen.

let Stack = createStackNavigator({
    tabs:{
      screen: Tabs, //You can add the NavigationOption here with navigation as parameter using destructuring.
      navigationOptions: ({navigation})=>{
       //title: (navigation.state.routes[navigation.state.index])["routeName"]  
       //this will fetch the routeName of Tabs in TabNavigation. If you set the routename of the TabNavigation as your Header. 

       //use the following title property,this will fetch the current stack's routeName which will be set as your header in the TabBar.

        //title: (navigation.state.routes[navigation.state.index]["routes"])[(navigation.state.routes[navigation.state.index]["index"])].routeName

       //you can use switch case,on matching the route name you can set title of the header that you want and also header left and right icons similarly.

        switch ((navigation.state.routes[navigation.state.index]["routes"])[(navigation.state.routes[navigation.state.index]["index"])].routeName) {
            case "Screen1":
                return {
                    title: "Home", 
                    headerLeft: (<Button
                        onPress={()=> alert("hi")}
                        title="Back"
                        color="#841584"
                        accessibilityLabel="Learn more about this purple button"
                    /> ),
                    headerRight: <Button title= "Right"/>
                }
            case "Screen2":
                return { 
                    title: "Profile",
                    headerLeft: (<Button
                        onPress={()=> alert("hi")}
                        title="Back"
                        color="#841584"
                        accessibilityLabel="Learn more about this purple button"
                    /> ),
                    headerRight: <Button title= "Right"/>
                }
            default:
                return { title: (navigation.state.routes[navigation.state.index]["routes"])[(navigation.state.routes[navigation.state.index]["index"])].routeName }
        }
      }
    },
    otherScreen:{
      screen: OtherScreen
    }
})

// navigationOptions

  navigationOptions: ({navigation})=>{
   //title: (navigation.state.routes[navigation.state.index])["routeName"]  
   //this will fetch the routeName of Tabs in TabNavigation. If you set the routename of the TabNavigation as your Header. 

   //use the following title property,this will fetch the current stack's routeName which will be set as your header in the TabBar.

    //title: (navigation.state.routes[navigation.state.index]["routes"])[(navigation.state.routes[navigation.state.index]["index"])].routeName

    switch ((navigation.state.routes[navigation.state.index]["routes"])[(navigation.state.routes[navigation.state.index]["index"])].routeName) {
        case "Screen1":
            return {
                title: "Home", 
                headerLeft: (<Button
                    onPress={()=> alert("hi")} //Here you can able to set the back behaviour.
                    title="Back"
                    color="#841584"
                    accessibilityLabel="Learn more about this purple button"
                /> ),
                headerRight: <Button title= "Right"/>
            }
        case "Screen2":
            return { 
                title: "Profile",
                headerLeft: (<Button
                    onPress={()=> alert("hi")} 
                    title="Back"
                    color="#841584"
                    accessibilityLabel="Learn more about this purple button"
                /> ),
                headerRight: <Button title= "Right"/>
            }
        default:
            return { title: (navigation.state.routes[navigation.state.index]["routes"])[(navigation.state.routes[navigation.state.index]["index"])].routeName }
    }
  }    

//alert(navigation.state)

{

    "routes":[
        {
            "key":"Screen1",
            "routeName":"Screen1",
            "routes":[
                {
                    "key":"Home",
                    "routeName":"Home",
                }
            ],
            "index":0,
            "isTransitioning":false,
            "key":"id-1530276062643-0"
        },
        {
            "key":"Screen2",
            "routeName":"Screen2",
            "routes":[
                {
                    "key":"Profile",
                    "routeName":"Profile",
                }
            ],
            "index":0,
            "isTransitioning":false,
            "key":"id-1530276062643-0"
        }
    ],
    "index":0,
    "isTransitioning":false,
    "routeName":"tabs",
    "key":"id-1530276062643-0"

}

//(navigation.state.routes[navigation.state.index])["routeName"] //(navigation.state.routes[navigation.state.index]["routes"])[(navigation.state.routes[navigation.state.index]["index"])].routeName

this will give the current route name of the tab inside StackNavigation.

上面的代码将在根堆栈标题中设置标题,其中TabBar作为第一个路由驻留,因此我们将标题设置为null,用于TabBar中的单个堆栈。通过使用这种方式将在TabBar中切换屏幕时提供动画,因为标题将保持静态。

你可以在这里找到工作副本https://www.dropbox.com/s/jca6ssn9zkzh9kn/Archive.zip?dl=0

下载此文件并执行以下操作。

  1. npm install //获取依赖项
  2. react-native upgrade //获取android和ios文件夹
  3. react-native链接//链接依赖项和库
  4. react-native run-ios(或)react-native run-android 你可以使用上面的,如果有的话,让我知道。

2
投票

您可以使用您当前的导航堆栈配置实现所需的行为。你可能需要改变几件事情并结合几个属性,但是当你得到它时,它就相当简单了。

我试着用一个小例子来解释它。

考虑下面的导航员;

const Tabs = createBottomTabNavigator({
    screen1: Tab1,
    screen2: Tab2
})

const Stack = createStackNavigator({
    tabs: {
      screen: TabsPage,
      navigationOptions: ({navigation}) => {
        return { title: (navigation.state.params && navigation.state.params.title ? navigation.state.params.title : 'No Title' ) }
      }
    },
    otherScreen: Page
})

如您所见,我正在从导航状态设置title参数。为了成为该导航员的参数,我们将从screenProps财产获得帮助;

class TabsPage extends Component {
  onTabsChange = (title) => {
    this.props.navigation.setParams({ title })
  }
  render() {
    return(<Tabs screenProps={{ onTabsChange: this.onTabsChange }} />)
  }
}

我为tab导航器创建了一个包装器组件,并传递了一个设置title参数的函数。

对于最后一部分,我们需要知道如何以及何时使用我们传递的函数。为此,我们将使用addListener导航道具

class Tab1 extends React.Component {
  setTitle = () => {
    this.props.screenProps.onTabsChange('Title from Tab 1')
  }
  componentDidMount() {
    this.props.navigation.addListener('willFocus', this.setTitle)
  }
  render() {
    return <View><Text>{'Tab1'}</Text></View>
  }
}

当我们的选项卡聚焦时,传递的函数将运行,然后设置该选项卡的标题。您可以使用此过程为标题设置不同的按钮或图标。你可以找到工作小吃here


0
投票

在AppNavigation.js //或您已定义路线的位置。

let Tabs = createBottomTabNavigator({
    screen1: Screen1,
    screen2: Screen2
})

let Stack = createStackNavigator({
    tabs: Tabs
    otherScreen: OtherScreen
},{
    headerMode:"float", //Render a single header that stays at the top and animates as screens are changed. This is a common pattern on iOS.
    headerTransitionPreset:"fade-in-place" //this will give a slight transition when header icon change.
  }
)

在Screen1.js中

class Screen1 extends Component {
 
 static navigationOptions = ({ navigation }) => {

    return {
      ...
      headerLeft: <HeaderLeftImage navigation={navigation} image={"Image_For_Screen1"}/>,
      ...
    }
  }
  ...
}

注意:您可以添加title,headersStyle,headerRight以相同的方式阅读此链接header configuration以获取更多详细信息

在Screen2.js中做类似于Screen1

class Screen2 extends Component {
 
 static navigationOptions = ({ navigation }) => {

    return {
      ...
      headerLeft: <HeaderLeftImage navigation={navigation} image={"Image_For_Screen2"}/>,
      ...
    }
  }
  ...
}

Header.js

export const HeaderLeftImage = (props) => (
    <View style={{
       'add styles'
    }}>
        <TouchableOpacity onPress={() => {"Add action here" }}>
            <Image source={props.image} resizeMethod='resize' style={{ height: 30, width: 90, resizeMode: 'contain' }} />
        </TouchableOpacity>
    </View>
)

希望这会有所帮助,如果您对代码有任何疑问,请随时提出。


0
投票
const RootStack = createStackNavigator(
  {
    Home: {screen: HomeScreen},
    FilterScreen: createMaterialTopTabNavigator({
        Tab1: {screen:Tab1Screen},
        Tab2: {screen: Tab2Screen},
    }),
  },
  {
    mode: 'modal',
    headerMode: 'none',
  }
);


render() {
    return <RootStack/>;
}

0
投票

如果您使用反应导航<2,即1.5。*您可以这样设置。

const Tabs = TabNavigator({
    Tab1:{
         screen: Tab1,
         navigationOptions: ({navigation}) => {
            return { title: "Tab 1 Heading", tabBarLabel:"Tab 1 "}
    },
    }
    Tab2:{
       screen: Tab2
       navigationOptions: ({navigation}) => {
         return { title: "Tab 2 Heading", tabBarLabel:"Tab 2 "}
    }
    }
})

const Stack = StackNavigator({
    tabs: {
      screen: Tabs
      navigationOptions: ({navigation}) => {
        return { title: "Stack"}
      }
    },
    otherScreen: Page
})

我不确定为什么他们删除了这个功能,当你尝试同样的功能时,它将不能用于最新的反应导航。现在标题对象键似乎用于后备。

这可能对某些用户有所帮助。如果您希望也可以尝试降级。

我为我的项目升级了React Navigation我觉得这样对某人有用

const Tabs = TabNavigator({
     Tab1:{
        screen: Tab1,
        navigationOptions: ({navigation}) => {
           return { tabBarLabel:"Tab 1 "}
        }},
     Tab2:{
        screen: Tab2
        navigationOptions: ({navigation}) => {
           return { tabBarLabel:"Tab 2 "}
        }}
});
Tabs.navigationOptions = ({navigation})=>{
    const { routeName } = navigation.state.routes[navigation.state.index]; //This gives current route
    switch(routeName){
         case "Tab1":
           headerTitle="Tab 1";
           break;
         case "Tab1":
           headerTitle="Tab 1";
           break;
    }

 return {
   headerTitle: headerTitle
}
}
© www.soinside.com 2019 - 2024. All rights reserved.