最近寫了個(gè)新rn項(xiàng)目廓啊,項(xiàng)目要求是rn內(nèi)嵌一個(gè)webview網(wǎng)頁實(shí)現(xiàn)全部業(yè)務(wù)需求~~鑒于網(wǎng)頁頁面數(shù)量較多聪姿,這就涉及到頁面的跳轉(zhuǎn)朴下、返回上頁以及退出APP的問題囱嫩,由于不做處理的話點(diǎn)擊手機(jī)的返回按鈕會(huì)直接退出APP,故在網(wǎng)上搜索了相應(yīng)的解決方案儿捧,為防止誤導(dǎo)大家荚坞,就不貼圖了,總之菲盾,無非都是抄來抄去還是錯(cuò)的颓影,按照其寫法,多近幾個(gè)頁面懒鉴,返回到網(wǎng)頁首頁以后就得多點(diǎn)n次才能退出APP诡挂,差評,經(jīng)過一番操作調(diào)試临谱,貼上本人代碼
export?default?class?App?extends?Component<Props>?{
??constructor(props){
????super(props);
????this.state?=?{
??????backButtonEnabled:false,
??????clicked:false,
????};
}
??onNavigationStateChange?=?navState?=>?{
????this.state.backButtonEnabled=?navState.canGoBack
??};
??render()?{
????return?(
??????<>
??????<StatusBar?backgroundColor="#EB0000"?barStyle="light-content"?translucent={true}?/>
??????<WebView
????????source={{?uri:?********'?}}
????????style={styles.container}
????????ref="webView"
????????onNavigationStateChange={this.onNavigationStateChange}
????????/>
??????</>
????);
??}
??//?監(jiān)聽原生返回鍵事件
??componentDidMount()?{
????setTimeout(()=>{
??????SplashScreen.hide()
????}?,2000);
?this.setState({
??clicked:false
?})
????if?(Platform.OS?===?'android')?{
??????BackHandler.addEventListener('hardwareBackPress',?this.onBackAndroid);
????}
??}
??onBackAndroid?=?()?=>?{
????console.log(this.state.backButtonEnabled)
????if?(this.state.backButtonEnabled)?{
??????this.refs['webView'].goBack();
??????return?true;
????}?else?{
??????if?(this.state.clicked)?{
????????//點(diǎn)過一次了璃俗。
????????console.log('back')
????????return?false;
??????}
??????this.state.clicked=true
??????ToastAndroid.show('再按一次退出應(yīng)用',?ToastAndroid.SHORT);
??????return?true;
????}
??};
}
親測可用