我想知道,是否可以只为1个组件运行脚本?
在我的代码中,我导入了5个组件
import React from 'react';
import Intro from './includes/Intro';
import Counter from './includes/Counter';
import Feedback from './includes/Feedback';
import FeedbackAll from './includes/FeedbackAll';
import Faq from './includes/Faq';
class Home extends React.Component {
render() {
return(
<main>
<Intro />
<Counter />
<Feedback />
<FeedbackAll />
<Faq />
</main>
)
}
}
export default Home
所以我有一些只想为组件<Counter />
运行的脚本
当我在该组件中编写该脚本时,该脚本将在项目的每个组件中运行。
这是文件Counter.js
import React from 'react';
const Counter = () => {
return (
<section id="benefits">
</section>
);
};
window.addEventListener('scroll', function() {
let hT = document.querySelector("#benefits").offsetTop;
alert (hT)
});
export default Counter
当我浏览另一个页面时,在滚动时脚本仍然有效,并查找元素#benefits,并显示错误。
所以我只需要在组件Counter.js
内运行该脚本
请帮助我做到这一点!