[英]Need access to state in Bottom Tab Navigator in React Native to implement Cart Badge
Is there a way to possibly access the redux state in the Bottom Tab Bar Navigator so a badge that takes a variable can be implemented.有没有办法在底部选项卡栏导航器中访问 redux state 以便可以实现带有变量的徽章。 This is the type of badge that is to be implemented on a bottom tab bar, particularly the cart icon so it can indicate the number of items in the cart.
这是要在底部选项卡栏上实现的徽章类型,尤其是购物车图标,因此它可以指示购物车中的商品数量。
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
/>
)
}
},
My solution is create a separate component called CartIcon
which will be connected to the redux store and set this as tabBarIcon
.我的解决方案是创建一个名为
CartIcon
的单独组件,它将连接到 redux 存储并将其设置为tabBarIcon
。 You can create CartIcon
component as below :您可以创建
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);
Now, In your router Cart
component as that icon component as below :现在,在您的路由器
Cart
组件中作为该图标组件,如下所示:
Cart: {
screen: Cart,
navigationOptions: {
tabBarIcon: ({ tintColor }) => (
<CartIcon /> //set cart icon
)
}
},
I faced the same situation and find a solution using DeviceEventEmitter
我遇到了同样的情况并使用
DeviceEventEmitter
找到了解决方案
Listner
in the bottom nav底部导航中的
Listner
const [count, setCount] = React.useState();
DeviceEventEmitter.addListener('newValue', v => {
v != undefined ? setCount(v) : null;
});
updated that count using使用更新计数
DeviceEventEmitter.emit('newValue', 5); // value is 5
✌ ✌
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.