如何在 React Native 的 WebView 的 onShouldStartLoadWithRequest() 中访问 this.setstate?

How to access this.setstate in onShouldStartLoadWithRequest() of a WebView in React Native?

我真的很难理解如何在执行特定操作时读取和设置 WebView 调用的函数内部的 this.state。我的最终目标是:

我是 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://whosebug.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;

要在 _onShouldStartLoadWithRequest 中访问更正此(class 上下文),您需要 bind 它与 class 上下文,绑定后每当调用此方法时 this里面的关键字会指向react class。

像这样:

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

或像这样使用 arrow function

onShouldStartLoadWithRequest={this._onShouldStartLoadWithRequest}

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

或者像这样:

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

查看此答案了解更多详情: