我的应用正在使用最新的基于钩子的React Navigation(v5.4.0)实现。它具有一个选项卡栏导航器,该导航器具有一个表示邮件消息的选项卡,并且在图标的拐角处显示了必填的消息数。选项卡代码类似于:
var messageCount = 0;
export function UpdateMessageCount(newnum:number)
{
messageCount = newnum;
}
function MessageIcon (color:string, size:number)
{
return (messageCount < 1)? (<FontAwesome style={{color:color, fontSize:size}} icon={LightIcons.envelope} pro={true} />):
(<View>
<FontAwesome style={{color:color, fontSize:size}} icon={LightIcons.envelope} pro={true} />
<View style={{position:'absolute',borderRadius:20, right:-10,top:0,backgroundColor:'red',minWidth:15, height:15, justifyContent:'center', alignItems:'center'}}>
<Text style={{fontSize:11, color:'white', fontFamily:'Roboto-Medium',marginLeft:2,marginRight:2}}>{messageCount}</Text>
</View>
</View>)
}
和
const MainTab = createBottomTabNavigator();
function MainTabNavigator() {
return (
<MainTab.Navigator
...
<MainTab.Screen name="Messages"
component={ MessageListNavigator }
options={{
tabBarIcon: ({ color, size }) => (
MessageIcon(color, size)
),
}}/>
我希望图标/选项卡导航器在邮件数量已更改时刷新(通过同步异步发生)。在导航器上设置伪造的选项(如下所示)将引起标签导航器的刷新,但依赖于未记录的副作用:
UpdateMessageCount(count);
let op = this.props.navigation.dangerouslyGetParent();
op.setOptions({tickle:""})
1)是否有其他方法可以告诉选项卡导航器/图标刷新? (我没有使用redux)
2)有没有办法从主导航器对象获取到嵌套的标签导航器的句柄?
预先感谢您的建议和评论。
答案 0 :(得分:0)
我通过在消息计数更改时发出事件并在选项卡导航器挂钩中捕获事件来解决此问题。稍作修改的代码如下:
function MessageIcon (messageCount:number, color:string, size:number)
{
return (messageCount < 1)? (<FontAwesome style={{color:color, fontSize:size}} icon={LightIcons.envelope} pro={true} />):
(<View>
<FontAwesome style={{color:color, fontSize:size}} icon={LightIcons.envelope} pro={true} />
<View style={{position:'absolute',borderRadius:20, right:-10,top:0,backgroundColor:'red',minWidth:15, height:15, justifyContent:'center', alignItems:'center'}}>
<Text style={{fontSize:11, color:'white', fontFamily:'Roboto-Medium',marginLeft:2,marginRight:2}}>{messageCount}</Text>
</View>
</View>)
}
const MainTab = createBottomTabNavigator();
function MainTabNavigator() {
const [messageCount, setMessageCount] = useState(0);
const messageCountListener = MyEvents.addListener(MyEventMessageCountUpdated,
(count)=>{
console.log("message count update: ", count)
setMessageCount(count);
});
useEffect(()=> {
return function cleanup() {
messageCountListener.remove();
}
});
return (
<MainTab.Navigator
...
<MainTab.Screen name="Messages"
component={ MessageListNavigator }
options={{
tabBarIcon: ({ color, size }) => (
MessageIcon(messageCount, color, size)
),
}}/>