【问题标题】:eventListener for hashChangehashChange 的事件监听器
【发布时间】:2017-01-20 21:35:27
【问题描述】:

我正在尝试在 ReactJS 中为我​​的页面添加一个事件侦听器。我已将它添加到 componentDidMount()。但仅在初始页面加载时触发。

如何在地址栏发生变化时触发它。

componentDidMount:function(){

        window.addEventListener("hashchange", console.log('hashchange1'));
        $(window).bind("hashchange", console.log('$ - hashchange'));
        window.onhashchange =  console.log('hashchange3');      
        ReactDOM.findDOMNode(this).addEventListener('hashChange',console.log('ReactDOM - hashchange'));
    },

我尝试了几种不同的方法来让它工作,但它们都只在第一次加载时工作。我做错了什么?

谢谢。

【问题讨论】:

    标签: reactjs addeventlistener hashchange


    【解决方案1】:

    您只是在每种情况下都执行console.log,并将其返回值添加为侦听器。你需要传递一个函数作为事件监听器,例如:

    window.addEventListener("hashchange", e => console.log('hashchange1', window.location.hash ));
    

    https://jsfiddle.net/ku6okrp2/

    使用 ES5 编辑使其看起来更明显:

    window.addEventListener("hashchange", function(e){ 
      console.log('hashchange1', window.location.hash )
    });
    

    【讨论】:

    • 啊,我明白了,我没有正确理解它。认为函数(console.log)仍然会被调用,但我想它需要一个事件。谢谢。
    • @fractal5 好吧,您可以将console.log 作为事件侦听器传递,就像任何其他函数一样,如果您不执行它:window.addEventListener("hashchange", console.log ); jsfiddle.net/ku6okrp2/1
    猜你喜欢
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2014-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-21
    • 2014-08-23
    相关资源
    最近更新 更多