erw*_*wan 32 android react-native
我有一个NavigatorAndroid反应原生应用程序.
我正在使用navigator.push()导航到另一个页面.后退按钮会弹出导航器并返回一页似乎很自然,但这不是正在发生的事情(退出应用程序).
反应本机Navigator真的没有后退按钮支持,我需要自己插入BackAndroid吗?
kar*_*kar 49
除了上面的回答,处理代码应该是这样的
var navigator;
React.BackAndroid.addEventListener('hardwareBackPress', () => {
if (navigator && navigator.getCurrentRoutes().length > 1) {
navigator.pop();
return true;
}
return false;
});
Run Code Online (Sandbox Code Playgroud)
在渲染代码中:
<Navigator ref={(nav) => { navigator = nav; }} />
Run Code Online (Sandbox Code Playgroud)
Max*_*lll 16
不确定API何时发生变化但是反应原生0.31(可能是早期版本)BackAndroid是必须从react-native导入的组件:
import {..., BackAndroid} from 'react-native'
另外一定要删除componentWillUnmount上的监听器:
componentWillUnmount(){
BackAndroid.removeEventListener('hardwareBackPress', () => {
if (this.navigator && this.navigator.getCurrentRoutes().length > 1) {
this.navigator.pop();
return true;
}
return false;
});
}
Run Code Online (Sandbox Code Playgroud)
*更新:在本机反应0.44中,此模块已重命名为BackHandler.Navigator也已被正式弃用,但仍可在此处找到:https://github.com/facebookarchive/react-native-custom-components
import { BackHandler } from 'react-native';
Run Code Online (Sandbox Code Playgroud)
别忘了绑[this]
正确答案应该是:
export default class MyPage extends Component {
constructor(props) {
super(props)
this.navigator = null;
this.handleBack = (() => {
if (this.navigator && this.navigator.getCurrentRoutes().length > 1){
this.navigator.pop();
return true; //avoid closing the app
}
return false; //close the app
}).bind(this) //don't forget bind this, you will remember anyway.
}
componentDidMount() {
BackAndroid.addEventListener('hardwareBackPress', this.handleBack);
}
componentWillUnmount() {
BackAndroid.removeEventListener('hardwareBackPress', this.handleBack);
}
render() {
return (
<Navigator
ref={navigator => {this.navigator = navigator}}
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
30482 次 |
| 最近记录: |