简体   繁体   中英

how to import Helper class in react

I am creating a helper class in react. The image below shows my setup:

在此输入图像描述

In my App.js, I have:

import  Helpers  from './Helpers.js'

I have also tried:

 import  Helpers  from './components/Helpers.js'
 import  Helpers  from 'src/components/Helpers.js'
 import  Helpers  from './components/Helpers.js'
 import  Helpers  from 'src/components/Helpers.js'
 import  {Helpers}  from './components/Helpers.js'
 import  {Helpers}  from 'src/components/Helpers.js'

and I have also tried, in my Helpers.js:

export default Helpers
export default Helpers();

However, I receive an error message:

'./Helpers.js' does not contain an export named 'Helpers'.

It seems as though App.js can not find and locate this class. How can I import it, so i can just call the functions, like:

Helpers.helperFunctionHere();

thanks.

Option 1: Export each function individually

In Helpers.js

export function helperFunctionHere() {
    console.log("hello there");
}

In App.js

import {helperFunctionHere} from "./Helpers";

render() {
    helperFunctionHere();
}

Option 2: Static properties on the class

In Helpers.js

class Helpers {
    static helperFunctionHere() {
        console.log("hi");
    } 
}
export default Helpers

In App.js

import Helpers from "./Helpers";

render() {
    Helpers.helperFunctionHere();
}

Should be export default Helpers . Am also assuming that your bundler is setup correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM