首页 > 解决方案 > 找不到变量:onClassifyPress

问题描述

我是 react-native 的新手,它给了我这个错误(找不到变量:onClassifyPress),我不知道如何解决它。我想要一个带有我在那里实现的两个按钮的屏幕。我的猜测是我在 onClassiyPress 函数中遗漏了一些东西,但我不确定。请帮我。

import React, {
    useState
} from 'react';
// Import core components

import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Button,
    Alert
} from 'react-native';

import DocumentPicker from 'react-native-document-picker';


const App = () => {

  onDocumentPress = async() => {
    try {
        let urlOfS = 'http://10.0.2.2:5000/fileupload'; // your url
        const res = await DocumentPicker.pick({
            type: [DocumentPicker.types.allFiles],
        })
        if (res.size < 50000000) {
            let data = new FormData();
            data.append('file', res)
            try {
                const responseOfFileUpload = await fetch(urlOfS, {
                    method: 'POST',
                    headers: {
                        Accept: 'application/json',
                        'Content-Type': 'multipart/form-data',
                    },
                    body: data,
                })
                if (responseOfFileUpload.status == 200) {
                    let responseInJs = await responseOfFileUpload.json();
                    let fileName = responseInJs.fileName; // file name which will be        sent from backend
                    let raspuns_server = responseInJs.answer;
                    console.log(raspuns_server);
                    alert('Upload Succesfull');
                } else {
                    alert('Upload Failed');
                }
            } catch (err) {
                alert('Upload Failed - Request nu a fost trimis');
                console.log(err, 'error in upload');
            }
        } else {
            alert('File size should not exceed 50 MB');
        }
    } catch (err) {
        if (DocumentPicker.isCancel(err)) {
            alert('No document selected');
        } else {
            throw err;
        }
    }
  }

  onClassifyPress = async() => {
    let urlOfS = 'http://10.0.2.2:5000/classy';
  }

  return (
    <div>
      <Button title="select document" onPress={this.onDocumentPress} />
      <Button title="classify song" onPress={this.onClassifyPress} />
    </div>
  );

};

export default App;

标签: react-native

解决方案


this 关键字引用类的当前实例,要访问类的方法或属性,您可以通过 this 关键字来执行此操作。因此,像您一样创建 onClassifyPress 是在创建一个需要访问类实例的方法,但是由于您的组件是函数,因此请在其中创建函数,如下所示:

  const onClassifyPress = async() => {
    let urlOfS = 'http://10.0.2.2:5000/classy';
  }

  // and call it without this keyword like this
  <Button title="classify song" onPress={onClassifyPress} />

推荐阅读