js监听孩子节点的数量:MutationObserver

定义监听方法

 //监测孩子数量
  const mutationObserver = new MutationObserver(mutations => {
    mutations.forEach(mutation => {
      if (mutation.type === 'childList') {
        setChildrenLength(roomButtonGroupRef.current?.childNodes?.length)
      }
    });
  });

监听及卸载

useEffect(() => {
    //监听
    mutationObserver.observe(roomButtonGroupRef.current, { childList: true });
    // 初始化子节点计数
    setChildrenLength(roomButtonGroupRef.current?.childNodes?.length)
    return () => {
      mutationObserver.disconnect()
    }
  }, [])

 

posted @ 2024-06-24 14:54  SimoonJia  阅读(3)  评论(0编辑  收藏  举报