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:
我在尝试创建一个幻灯片,在幻灯片中。我有一个增加当前滑动指数的函数,如下所示:
function plusSlides(n) {
showSlides(slideIndex += n);
}
In Homepage.jsx
, I have a "next" button that should call plusSlides
from slideshow.js
when it is clicked, like so:
在主页。jsx,我有一个“下一步”按钮,应该从幻灯片调用plusSlides。点击时的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>
);
}
}
1 个解决方案
#1
19
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);
}
#1
19
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);
}