首页 > 解决方案 > 如何在 b.js 的按钮中使用 a.js 中的函数?

问题描述

当用户点击按钮时,我正在尝试打开上传文档对话框。我从另一个文件(“upload-recording-button.js”)导入函数来执行此操作,并尝试在按钮中使用它。但是,我遇到了一些错误,例如“_uploadRecordingButton.uploadRecording 未定义”。</p>

基于其他相关的 Stack Overflow 页面,我尝试将按钮的 OnPress 更改为 this.uploadRecording、uploadRecording(this)、this.uploadRecording(),可能还有其他一些变体。它们都因“功能不存在”的变体而失败。</p>

这是我正在调用的函数的文件的一部分:

上传-录音-button.js

import React, {Component} from 'react';
import { DocumentPicker } from 'expo';

async function uploadRecording() {
  let result = await DocumentPicker.getDocumentAsync({type: '*/*'});

  if (!result.cancelled) {
    //upload function(result.uri);
  }
}

export default uploadRecording;

主文件


import { uploadRecording } from '../components/upload-recording-button';

export default class HomeScreen extends React.Component {
  static navigationOptions = {
    //header: null,
    title: 'Recents',
    // uploadRecording(this)
    headerRight: (
      <Button
        onPress={uploadRecording()}
        title="Add"
        color="#007AFF"
      />
    ),
  };

标签: javascriptreactjsreact-nativeexpo

解决方案


您需要从中导出功能upload-recording-button.js

import React, {Component} from 'react';
import { DocumentPicker } from 'expo';

export async function uploadRecording() {
  let result = await DocumentPicker.getDocumentAsync({type: '*/*'});

  if (!result.cancelled) {
    //upload function(result.uri);
  }
}

如果您只导出一个函数,upload-recording-button.js则可以使用默认导出

export default function-name

并将其导入您要使用的文件中

import anyName from file-fath

推荐阅读