如何在React中仅针对1个组件运行自定义js代码?

时间:2019-01-21 22:10:58

标签: reactjs

我想知道,是否可以只为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内运行该脚本

请帮助我做到这一点!

1 个答案:

答案 0 :(得分:0)

您应该将counter.js重构为类组件。技巧是在类定义内移动事件监听器,并在卸载类时删除事件监听器。

现在仅在用户<Counter />的页面中,附加了滚动侦听器,并且在卸载<Counter />组件时将其删除。

解决方案

Edit 6w30wwqwxw