从React中的另一个文件调用JS函数? [英] Call JS function from another file in React?
本文介绍了从React中的另一个文件调用JS函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在一个单独的JavaScript文件中有一个函数,我想在React组件中调用 - 我该如何实现?
I have a function in a separate JavaScript file that I would like to call in a React component - how can I achieve this?
我正在尝试创建幻灯片显示,在 slideshow.js
中,我有这个函数可以增加当前的幻灯片索引,如下所示:
I'm trying to create a slideshow, and in slideshow.js
, I have this function that increases the current slide index, like so:
function plusSlides(n) {
showSlides(slideIndex += n);
}
在 Homepage.jsx
,我有一个下一步按钮,点击它时应该从 slideshow.js
调用 plusSlides
,就像这样:
In Homepage.jsx
, I have a "next" button that should call plusSlides
from slideshow.js
when it is clicked, like so:
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>
);
}
}
推荐答案
你可以导出它,或者我错过了你的问题
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 './slide'
handleClick (event) {
plusSlides(1);
}
这篇关于从React中的另一个文件调用JS函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文