2017-04-12 113 views
1

我真的很努力去理解如何在執行特定操作時,通過WebView調用的函數內部讀取和設置this.state。我的最終目標是:如何在React Native中訪問WebView的onShouldStartLoadWithRequest()中的this.setstate?

  • 顯示一個活動指示燈,當用戶點擊web視圖
  • 執行基於用戶對

點擊URL某些行爲我很裏面的鏈接對React來說是新的,但根據我所瞭解的內容,我應該使用() => function將主對象的this綁定到函數內部。

這對onLoad={(e) => this._loading('onLoad Complete')}有效,我可以在第一次加載頁面時更新狀態。

如果我使用onShouldStartLoadWithRequest={this._onShouldStartLoadWithRequest}我可以看到它的工作原理和我的console.warn()顯示在屏幕上。 this.state當然不可用。

但是,如果我將其更改爲onShouldStartLoadWithRequest={() => this._onShouldStartLoadWithRequest}該函數似乎根本不會被執行,並且既不會運行this.state(在下面的代碼中註釋)或console.warn()。

任何幫助表示讚賞!

import React, { Component} from 'react'; 
import {Text,View,WebView} from 'react-native'; 

class Question extends Component { 
    constructor(props) { 
     super(props); 
     this.state = { 
      isLoading: false, 
      debug: 'Debug header' 
     }; 
    } 

    render() { 
     return (
      <View style={{flex:1, marginTop:20}}> 
       <Text style={{backgroundColor: '#f9f', padding: 5}}>{this.state.debug}</Text> 
       <WebView 
        source={{uri: 'http://stackoverflow.com/'}} 
        renderLoading={this._renderLoading} 
        startInLoadingState={true} 
        javaScriptEnabled={true} 
        onShouldStartLoadWithRequest={this._onShouldStartLoadWithRequest} 
        onNavigationStateChange = {this._onShouldStartLoadWithRequest} 
        onLoad={(e) => this._loading('onLoad Complete')} 
       /> 
      </View> 
     ); 
    } 

    _loading(text) { 
     this.setState({debug: text}); 
    } 

    _renderLoading() { 
     return (
      <Text style={{backgroundColor: '#ff0', padding: 5}}>_renderLoading</Text> 
     ) 
    } 

    _onShouldStartLoadWithRequest(e) { 
     // If I call this with this._onShouldStartLoadWithRequest in the WebView props, I get "this.setState is not a function" 
     // But if I call it with() => this._onShouldStartLoadWithRequest it's not executed at all, 
     // and console.warn() isn't run 
     //this.setState({debug: e.url}); 
     console.warn(e.url); 
     return true; 
    } 

} 



module.exports = Question; 

回答

2

要訪問正確的內_onShouldStartLoadWithRequest這個(類背景),你需要bind它與類背景下,結合每當這個方法被調用this關鍵字裏面將指向反應下課。

像這樣:

onShouldStartLoadWithRequest={this._onShouldStartLoadWithRequest.bind(this)} 

或使用arrow function這樣的:

onShouldStartLoadWithRequest={this._onShouldStartLoadWithRequest} 

_onShouldStartLoadWithRequest = (e) => {...} 

或者這樣:

onShouldStartLoadWithRequest={(e) => this._onShouldStartLoadWithRequest(e)} 

檢查這個答案詳細信息:Why is JavaScript bind() necessary?

+0

大, 一世t工作關於this.state綁定,但我得到**未定義不是一個對象(評估'e.url')**。該函數是'_onShouldStartLoadWithRequest(e)',並且應該包含e.url,它在我沒有綁定時做。 – Niclas

+0

檢查更新後的答案,如果需要通過'e'的箭頭函數,現在就試試。 btw第一種方式應該工作,當你使用'.bind(this)'。 –

+0

出於某種原因,第一個完美的作品,第二個返回未定義e.url。非常感謝你! – Niclas

相關問題