首页 > 解决方案 > 在 React Native 中检测活动屏幕

问题描述

对不起,我的英语不好。我在没有使用 React Navigation 中的 Tab Navigation 的情况下构建了一个导航栏,除了尝试设置“活动”图标外,一切正常导航。

我想我有点复杂了,但是我需要捕获活动屏幕以将其作为状态传递并将图标的颜色更改为“活动”,而其他的则禁用。我曾尝试使用 Detect active screen 和 onDidFocus 但我只收到有关转换的信息,我需要屏幕的名称或 ID。

我留下我的代码(这个组件被导出到我希望有导航栏的每个页面)。拜托,这个想法是不要使用 React Native Navigation 中的 Tab Navigation。

export default class Navbar extends Component {

/** Navigation functions by clicking on the icon (image) */
_onPressHome() {
    this.props.navigation.navigate('Main');
}

_onPressSearch() {

    this.props.navigation.navigate('Main');
}

render() {
    const { height, width } = Dimensions.get('window');
    return (
        <View style={{ flexDirection: 'row', height: height * .1, justifyContent: 'space-between', padding: height * .02 }}>
            /** Icon section go Home screen */
            <View style={{ height: height * .06, alignItems: 'center' }}>
                <TouchableOpacity
                    onPress={() => this._onPressHome()}
                    style={styles.iconStyle}>
                    <Image
                        source={HOME_ICON}
                        style={{ width: height * .04, height: height * .04, }} />
                    <Text style={[styles.footerText, { color: this.state.colorA }]}>Inicio</Text>
                </TouchableOpacity>
            </View>
            /** Icon section go Search screen */
            <View style={{ height: height * .06, alignItems: 'center' }} >
                <TouchableOpacity
                    onPress={() => this._onPressSearch()}
                    style={styles.iconStyle}>
                    <Image
                        source={SEARCH_ICON}
                        style={{ width: height * .04, height: height * .04, opacity: .6 }} />
                    <Text style={[styles.footerText, { color: this.state.colorB }]}>Inicio</Text>
                </TouchableOpacity>
            </View>
        </View>
    )
}
}

对于导航,我使用了 createStackNavigator 以及

const drawerNavigatorConfig = {
contentComponent: props => <CustomDrawerContentComponent {...props} 
/>,
};

const AppDrawer = createDrawerNavigator(drawerRouteConfig, 
drawerNavigatorConfig);

我不知道 createDrawerNavigator 是否在干扰某些东西,我读到它会生成额外的密钥。请帮我解决一下这个。

标签: reactjsreact-nativereact-navigation

解决方案


import { useIsFocused } from '@react-navigation/native';

function Profile() {
  const isFocused = useIsFocused();

  return <Text>{isFocused ? 'focused' : 'unfocused'}</Text>;
}

检查文档 https://reactnavigation.org/docs/use-is-focused/


推荐阅读