简体   繁体   中英

React.js / CRA, How to call or import a javaScript function from another file?

My code is getting longer so I decided to transfer them to other javaScript file.

I followed this relevant topic regarding my question but Why I getting an error i just copy and paste everything?

In above link here's the code

//slideshow.js
function plusSlides(n) {
    showSlides(slideIndex += n);
}

//Home.js
class NextButton extends React.Component {
    constructor() {
        super();
        this.onClick = this.handleClick.bind(this);
    }

    handleClick (event) {
        script.plusSlides(1); // I don't know how to do this properly...
    }

    render() {
        return (
            <a className="next" onClick={this.onClick}>
                &#10095;
            </a>
        );
    } 
}

This my error "Attempted import error: 'plusSlides' is not exported from '../plusSides file'."

I used react.js CRA is there something i need to configure to fix this?

It must have worked. Only thing you need is babel to transpile es6 (which I assume you have as you have used react CRA). There is another way of doing it, ie using default export

slideshow.js

export default (n)=>{
    showSlides(slideIndex += n);
}

and importing this function like this in Home.js

Home.js

import anyname from './slideshow.js' //I am assuming you have slideshow.js and Home.js in same directory

handleClick (event) {
    anyname(1); 
}

You really giving space followed by the word 'file'?? Don't you think it should be imported like:

import plusSlides from '../plusSides';

Also, see what you're exporting from that file. If it is a default import then you can import by any name you want, otherwise you have to give same names in the export and imports. Remember, you can only make one default export per file.

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