React Native问题传递函数

时间:2018-04-18 09:22:48

标签: javascript react-native

我是React Native的新手,我想要做的是,我想将getUPCfromApi(upc)传递给onScan函数内的ScanditSDK.js组件。但我得到这个错误请参阅附件img。 Screenshot of error message

Api.js

- (void)viewDidLoad {
    [super viewDidLoad];

    NSDictionary *userInfo = [DataManager getInstance].userInfo;
}

ScanditSDK.js包含扫描仪模块。在onScan方法中,我调用了我在Api.js中创建的getUpcFromApi(upc)

ScanditSDK.js

import React, { Component } from 'react';
import ScanditSDK from './components/ScanditSDK'

export default class Api extends Component{
  getUPCfromApi = (upc) => {
   try {
    let response = fetch(
      `https://api.upcdatabase.org/product/${upc}/API_KEY`);
    let responseJson = response.json();
    return responseJson;
    console.log('response',responseJson);
  }  catch (error) {
    console.error(error);
  }
 }
  render(){
   return(
   <ScanditSDK 
   getUPCfromApi={this.getUPCfromApi}
   />
   ) 
  }
}

1 个答案:

答案 0 :(得分:0)

您应该使用props来访问您的功能。更改您的onScan功能如下

onScan = (session) => {
    this.setState({upc:session.newlyRecognizedCodes[0].data })
    alert(session.newlyRecognizedCodes[0].data + " " + session.newlyRecognizedCodes[0].symbology);
    this.props.getUPCfromApi(this.state.upc)
  }

在您的Api组件中。在构造函数中绑定您的函数。

constructor(props){
super(props)
this.getUPCfromApi = this.getUPCfromApi.bind(this)
}