如何在reactjs中使用另一个js文件中的函数?

时间:2017-03-27 12:37:01

标签: javascript reactjs jsx

我有一个文件something.js,它有一个功能:

someFunction: function(arg1, arg2){
    //code blocks
}

在我的app.js文件中,我想在app类中调用此函数。我已导入something.js这样的文件import { someFunction } from './something.js';。现在我试图在app

中的函数中使用它
var res = someFunction("abc", 2); 
console.log(res);`

我收到错误Uncaught TypeError: (0 , _something.someFunction) is not a function

一些帮助将不胜感激。

4 个答案:

答案 0 :(得分:4)

您可以:在something.js文件中执行:module.exports = function(){}.. 并在您的app.js文件中:

const functionName = require('./path_to_your_file');

export default somethingFunction = {}以及app.js

import {somethingFunction} from '/.path_to_your_file'

让我知道这是否成功! :)

答案 1 :(得分:3)

要导入某些内容,您需要从其他模块导出它。 例如,您可以在something.js。{/ p>中export class YourComponent extends React.Component

然后在另一个文件中,您可以import { YourComponent } from './something'

例如,您可以在something.js中执行类似

的操作
const MyClass = {
    methodName() { return true; }
}

export { MyClass as default } // no semi-colon

然后在另一个文件中

import WhateverIWant from 'something';
WhateverIWant.methodName(); // will return true

编辑: 使用大量示例is available here进行深入解释。

答案 2 :(得分:3)

你需要这样写:

something.js档案 -

module.exports = {

   A: funtion(){
   },

   B: funtion(){
   }

}

然后像这样导入:

import {A} from 'something';

或者像这样使用它:

something.js档案 -

export A(){
}

export B(){
}

然后像这样导入:

import {A} from 'something';

阅读这篇文章:https://danmartensen.svbtle.com/build-better-apps-with-es6-modules

答案 3 :(得分:0)

something.js文件中,您可以在文件底部附近添加export someFunction。然后,这将允许您使用之前的import { someFunction } from './something.js';导入该功能。