我只想在某些页面中禁用Android Back按钮。我使用以下代码:
componentWillUnmount(){
//For disabling the back button on cellphone
BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton);
}
componentWillMount() {
ParkToolbar.init( this );
}
//For disabling the back button on cellphone
handleBackButton() {
ToastAndroid.show('you cannot return', ToastAndroid.SHORT);
return true;
}
componentDidMount() {
toolbarActiveItem = this.state.user;
ParkToolbar.setActiveItem(this.props.navigation.state.params.activeSection);
//For disabling the back button on cellphone
BackHandler.addEventListener('hardwareBackPress', this.handleBackButton);
}
问题是,当我在程序中使用一个页面(屏幕)中的代码时,在我的应用程序的每个部分中,将在所有页面(屏幕)中禁用返回按钮。您是否知道如何以一种仅禁用单个页面的返回按钮(屏幕)?
?更新:我还用Backandroid测试了代码,并发生了同样的问题。
以禁用Android设备后按钮,您可以这样做,它会处理后按下,只需在各自的活动中添加这些方法: -
import { BackHandler } from 'react-native';
constructor(props) {
super(props)
}
componentWillMount() {
BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonClick);
}
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', this.handleBackButtonClick);
}
handleBackButtonClick = () => {
this.props.navigation.goBack(null);
return true;
};
使用功能组件时,这对我有用(在此示例中,我想将硬件从详细信息服务中禁用)
) import {useRoute, useFocusEffect} from '@react-navigation/native';
import { BackHandler } from 'react-native'
function DetailService(props) {
const route = useRoute();
useFocusEffect(
React.useCallback(() => {
const onBackPress = () => {
if (route.name === 'DetailService') {
return true;
} else {
return false;
}
};
BackHandler.addEventListener('hardwareBackPress', onBackPress);
return () =>
BackHandler.removeEventListener('hardwareBackPress', onBackPress);
}, [route]),
);
......
我在react Native中使用useEffect
与导航。
useEffect(() => {
const unsubscribe = BackHandler.addEventListener('hardwareBackPress', handleBackButton);
return () => null
}, [])
export const handleBackButton = () => {
ToastAndroid.show('Back button is pressed', ToastAndroid.SHORT);
return true;
}
如果您不返回,则将在所有屏幕上禁用后退按钮。因此,请确保在屏幕从当前一个更改时卸载组件。
要禁用某些屏幕中的Android硬件后按钮,我们必须使用React-Native本身的反手键,我们必须使用React-Navigation的NavigationEvents参考。
import { BackHandler } from 'react-native';
import { NavigationEvents } from 'react-navigation';
_onBlurr = () => {
BackHandler.removeEventListener('hardwareBackPress',
this._handleBackButtonClick);
}
_onFocus = () => {
BackHandler.addEventListener('hardwareBackPress',
this._handleBackButtonClick);
}
_handleBackButtonClick = () => true
render() {
<View>
<NavigationEvents
onWillFocus={this._onFocus}
onWillBlur={this._onBlurr}
/>
{// Your View Here}
</View>
}
参考:https://facebook.github.io/reeact-native/docs/backhandlerhttps://reaectnavigation.org/docs/en/navigation-events.html
您需要将其放入组件中:
useEffect(() => {
BackHandler.addEventListener('hardwareBackPress', () => true);
}, []);
然后,按钮将在不触发动作的情况下按下。