【问题标题】:React Add event DOMContentLoaded with useEffect使用 useEffect 反应添加事件 DOMContentLoaded
【发布时间】:2020-05-24 13:01:06
【问题描述】:

我正在尝试在加载 DOM 后向元素添加事件侦听器,以便使用 Materialize CSS 的浮动操作按钮。

看下面的代码,效果函数被触发了,但是handleContentLoaded函数没有被触发。组件渲染没有错误。

这里缺少什么?这是使用此效果的正确方法吗?

  const handleContentLoaded = () => {
    console.log("handleContentLoaded fired");
    var elems = document.querySelectorAll(".fixed-action-btn");
    var instances = M.FloatingActionButton.init(elems, {});
    console.log("instances", instances);
  };

  useEffect(() => {
    console.log("using effect");
    document.addEventListener("DOMContentLoaded", handleContentLoaded);
  }, []);

【问题讨论】:

    标签: reactjs react-hooks materialize


    【解决方案1】:

    尝试移除 addEventListener,useEffect 在页面的所有元素都正确呈现后运行,你不需要任何监听器:

    useEffect(() => {
      console.log("using effect");
      handleContentLoaded();
    }, []);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-07
      • 2021-05-11
      • 2012-04-01
      • 2021-10-03
      • 2017-02-04
      • 2023-03-06
      • 2020-11-25
      • 1970-01-01
      相关资源
      最近更新 更多