问题描述
我试图添加在按下android后退按钮时返回webview的功能,但我仍然无法使其正常工作.
I am trying to add going back on webview when the android backbutton was pressed and I still couldn't manage to make it work.
这是我的代码:
<WebView
ref={WEBVIEW_REF}
source={source}
domStorageEnabled={true}
onNavigationStateChange={this.onNavigationStateChange}
/>
componentDidMount() {
BackAndroid.addEventListener('hardwareBackPress', function() {
if(this.state.backButtonEnabled) {
this.refs[WEBVIEW_REF].goBack();
return true;
}
});
};
onNavigationStateChange = (navState) => {
this.setState({
backButtonEnabled: navState.canGoBack,
});
};
使用上面的代码,我得到未定义的错误不是this.state.backButtonEnabled对象(已设置为状态).
With the code above I'm getting the error undefined is not an object this.state.backButtonEnabled (which is set in the state).
比起我只想看看goBack是否有效,所以我删除了if语句,然后得到的错误未定义不是this.refs [WEBVIEW_REF]对象.
Than I just wanted to see if the goBack works so I removed the if statement and than I was getting the error undefined is not an object this.refs[WEBVIEW_REF].
什么是最好的解决方案?
What is the best solution for this?
推荐答案
class MyComponent extends Component {
state = {};
componentDidMount(){
BackHandler.addEventListener('hardwareBackPress', this.backHandler);
}
componentWillUnmount(){
BackHandler.removeEventListener('hardwareBackPress', this.backHandler);
}
backHandler = () => {
if(this.state.backButtonEnabled) {
this.refs[WEBVIEW_REF].goBack();
return true;
}
}
}
1)绑定处理程序2)不要忘记在卸载时使用removeListener.
1) Bind your handler 2) Do not forget to removeListener on unmount.
这篇关于React-Native:回到android硬件后退按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!