首页 > 解决方案 > 如何在 React Native 中获取活动的 TabBarButton?

问题描述

我试图强调活动的文本,tabBarButton但它似乎没有提供focused prop. 我怎样才能做到这一点 ?

<Tab.Screen
          name="Home"
          component={HomeNavigator}
          options={() => ({
            title: 'Home',
            tabBarButton: (props) => (
              <TouchableWithoutFeedback {...props} >
                <View style={{flex:2, alignItems: 'center'}}>
                  <Image source={LOGO} resizeMode="contain" style={[styles.imgSize, props.focused && { opacity:1 }]} />
                  <Text style={[styles.label, props.focused && { opacity:1, textDecorationLine: 'underline' }]}>HOME</Text>
                </View>
              </TouchableWithoutFeedback>
            ),
          })}
        />

标签: react-native

解决方案


你应该把你包裹Tab.Screen在 aTab.Navigator中,因为focused道具在navigator(这里)

<Tab.Navigator
      initialRouteName={"Home"}

      screenOptions={({ route }) => ({
          tabBarIcon: ({ focused, color, size }) => {
            let imageStyle
            let textStyle

            if (route.name === "Home") {
              imageStyle = focused ? styles.activeImageStyle : styles.inactiveImageStyle
              textStyle = focused ? styles.activeTextStyle : styles.inactiveTextStyle
            }
            if (route.name === "OtherScreen") {
              imageStyle = focused ? styles.activeImageStyle : styles.inactiveImageStyle
              textStyle = focused ? styles.activeTextStyle : styles.inactiveTextStyle
            }

            return <TabBarIcon imageStyle={imageStyle} textStyle={textStyle}/>
          },
          headerStatusBarHeight: 0,

        }
      )}
      tabBarOptions={{
        showLabel: false,
        style: styles.tabBarStyle,
        keyboardHidesTabBar: true,
        safeAreaInsets: { bottom: 0 }
      }}
    >
    
  <Tab.Screen
          name="Home"
          component={HomeNavigator}
      
  />    
   <Tab.Screen
          name="OtherScreen"
          component={OtherNavigator}
      
  /> 

</Tab.Navigator>


// And your styles could be

const styles = export default StyleSheet.create({
 activeImageStyle: {...},
 inactiveImageStyle: {...},
 activeTextStyle: {...},
 inactiveTextStyle: {...}
 
 })

// Where you can declare you TabBarIcon in another file as being this 

 <TouchableWithoutFeedback {...props} >
                <View style={{flex:2, alignItems: 'center'}}>
                  <Image source={LOGO} resizeMode="contain" style={[styles.imgSize, props.imageStyle ]} />
                  <Text style={[styles.label, props.textStyle]}>HOME</Text>
                </View>
              </TouchableWithoutFeedback>


推荐阅读