React Navigation changing tab icons on tab navigator dynamically

走远了吗. 提交于 2019-12-12 04:01:35

问题


So I am new to react native and redux. The app is already configured (by someone else) to have react-navigation and redux. Now we're using a TabNavigator (bottom) for our menu and this TabNavigator also contains the Login button. Now what I want to do is when the user logs in, the Login button (with text and icon) becomes Logout.

Is there a way to do that? Also my TabNavigator is in a separate file.

What I want is something like this:

TabNavigator(
  {
    ...other screens,
    //show this only if not logged in
    Login: {
      screen: LoginScreen
    },
    //show this only if logged in
    Logout: {
      screen: //There should be no screen here just the logout functionality
    }
  },
  {...options here}
)

Thanks in advance.


回答1:


You can do it using Redux:

AuthIcon.js:

const LOGGED_IN_IMAGE = require(...)
const LOGGED_OUT_IMAGE = require(...)

class AuthIcon extends React.Component {
  render() {
    const { loggedIn, focused, tintColor } = this.props
     // loggedIn is what tells your app when the user is logged in, you can call it something else, it comes from redux
    return (
       <View>
         <Image source={loggedIn ? LOGGED_IN_IMAGE : LOGGED_OUT_IMAGE} resizeMode='stretch' style={{ tintColor: focused ? tintColor : null, width: 21, height: 21 }} />
      </View>
    )
  }
}

const ConnectedAuthIcon = connect(state => {
   const { loggedIn } = state.auth
   return { loggedIn }
})(AuthIcon)

export default ConnectedAuthIcon;

then inside your TabNavigator file:

import ConnectedAuthIcon from './AuthIcon.js'

export default TabNavigator({
  Auth: {
    screen: Auth,
    navigationOptions: ({ navigation }) => ({
      tabBarLabel: null,
      tabBarIcon: ({ tintColor, focused }) => <ConnectedAuthIcon tintColor={tintColor} focused={focused} />,
      title: "Auth"
    })
  }
})

Edit:

In your Auth.js:

class Auth extends React.Component {

  render() {
    const { loggedIn } = this.props
    if (loggedIn) {
      return <Profile />
    } else {
      return <Login />
    }
  }

}

export default connect(state => {
  const { loggedIn } = state.auth
  return { loggedIn }
})(Auth)


来源:https://stackoverflow.com/questions/46675964/react-navigation-changing-tab-icons-on-tab-navigator-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!