Javascript 从 React 中的另一个文件调用 JS 函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43262599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:47:43  来源:igfitidea点击:

Call JS function from another file in React?

javascriptreactjs

提问by Emily Yeh

I have a function in a separate JavaScript file that I would like to call in a React component - how can I achieve this?

我在一个单独的 JavaScript 文件中有一个函数,我想在 React 组件中调用它 - 我该如何实现?

I'm trying to create a slideshow, and in slideshow.js, I have this function that increases the current slide index, like so:

我正在尝试创建一个幻灯片,在 中slideshow.js,我有这个增加当前幻灯片索引的功能,如下所示:

function plusSlides(n) {
    showSlides(slideIndex += n);
}

In Homepage.jsx, I have a "next" button that should call plusSlidesfrom slideshow.jswhen it is clicked, like so:

Homepage.jsx,我有一个“下一步”按钮时应该调用plusSlidesslideshow.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>
        );
    } 
}

回答by KornholioBeavis

You can export it, or am I missing your question

您可以导出它,还是我错过了您的问题

//slideshow.js
export const plusSlides = (n)=>{
    showSlides(slideIndex += n);
}

and import it where you need to

并将其导入到您需要的地方

//Homepage.js
import {plusSlides} from './slideshow'

handleClick (event) {
        plusSlides(1); 
    }