如何在EventHandler函数内调用函数反应原生

时间:2018-04-24 01:22:19

标签: javascript

我在我的项目中实现了这个库https://github.com/elanic-tech/react-native-paytm。我成功地收到了Paytm的回复 onPayTmResponse但现在我想将此响应发送到服务器但在此函数内部,我无法调用任何函数或状态它给我一个未定义的错误。

componentWillMount() {
        if(Platform.OS == 'ios'){
            const { RNPayTm } = NativeModules
            const emitter = new NativeEventEmitter(RNPayTm)
            emitter.addListener('PayTMResponse', this.onPayTmResponse)
        }else{
            DeviceEventEmitter.addListener('PayTMResponse', this.onPayTmResponse)
        }

        //this.makeRemoteRequest();
}

onPayTmResponse(response) {
        // Process Response
        // response.response in case of iOS
        // reponse in case of Android

        var actual = "";
        if(Platform.OS == 'ios'){
            actual = JSON.parse(response.response);
        }else{
            actual = JSON.parse(response);
        }

        console.log(actual, this.state);

        if(actual.RESPCODE == "01"){
            // Place Order
            placeOrder();
        }else{
            alert(actual.RESPMSG);
            this.setState({loading: false, buttonText: 'Continue'});
        }
    }

Error

1 个答案:

答案 0 :(得分:0)

将您的onPayTmResponse功能绑定在componentWillMount

componentWillMount() {
  this.onPayTmResponse = this.onPayTmResponse.bind(this); // note: we bind onPayTmResponse with this
  if(Platform.OS == 'ios'){
    const { RNPayTm } = NativeModules
    const emitter = new NativeEventEmitter(RNPayTm)
    emitter.addListener('PayTMResponse', this.onPayTmResponse)
  }else{
    DeviceEventEmitter.addListener('PayTMResponse', this.onPayTmResponse)
  }
  //this.makeRemoteRequest();
}

现在你应该能够在onPayTmResponse内调用setState。