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
Call JS function from another file in React?
提问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,我有一个“下一步”按钮时应该调用plusSlides从slideshow.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}>
❯
</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);
}

