首页 > 解决方案 > 需要访问 React Native 中底部选项卡导航器中的状态以实现购物车徽章

问题描述

有没有办法在底部选项卡栏导航器中访问 redux 状态,以便可以实现带有变量的徽章。这是要在底部标签栏上实现的徽章类型,特别是购物车图标,因此它可以指示购物车中的商品数量。

    Cart: {
      screen: Cart,
      navigationOptions: {
        tabBarIcon: ({ tintColor }) => (
          <IconBadge
            MainElement={
              <Image
               source={require("./assets/icons/Cart.png")}
               style={{ height: 24, width: 24, tintColor: tintColor }}
               />
            }
            BadgeElement={
              <Text style={{color:'#FFFFFF'}}>{this.state.BadgeCount}</Text>
            }
            IconBadgeStyle={
             {width:30,
              height:30,
              backgroundColor: '#FF00EE'}
            }
            Hidden={this.state.BadgeCount==0}   //how can we get access to state/props/cartItems in the bottom tab bar
          />
        )
      }
    },

徽章

标签: javascriptreact-nativestatebadgenavigator

解决方案


我的解决方案是创建一个名为的单独组件CartIcon,该组件将连接到 redux 存储并将其设置为tabBarIcon. 您可以如下创建CartIcon组件:

class CartIcon extends Component {
  render() {
    return (
      <IconBadge
        MainElement={
          <Image
            source={require("./assets/icons/Cart.png")}
            style={{ height: 24, width: 24, tintColor: tintColor }}
          />
        }
        BadgeElement={
          <Text style={{ color: '#FFFFFF' }}>{this.props.cartReducer.items.length}</Text>
        }
        IconBadgeStyle={
          {
            width: 30,
            height: 30,
            backgroundColor: '#FF00EE'
          }
        }
        Hidden={this.props.cartReducer.items.length === 0}   //how can we get access to state/props/cartItems in the bottom tab bar
      />
    );
  }
}

const mapStateToProps = (state) => ({
  cart: state.cartReducer
});

export default connect(mapStateToProps, null)(CartIcon);

现在,在您的路由器Cart组件中作为该图标组件,如下所示:

Cart: {
  screen: Cart,
  navigationOptions: {
    tabBarIcon: ({ tintColor }) => (
      <CartIcon /> //set cart icon
    )
  }
},

推荐阅读