React(React Hook)+Typescript 监听d
2020-05-28 本文已影响0人
nomooo
主要用到的js技术部分:
MutationObserver
接口提供了监视对DOM树所做更改的能力。它被设计为旧的Mutation Events功能的替代品,该功能是DOM3 Events规范的一部分。
tsx部分:
使用了React hook的函数,详情见https://zh-hans.reactjs.org/docs/hooks-reference.html
import React, { useEffect, useRef, MutableRefObject } from 'react'
import './map.scss'
function addWatch(element: HTMLDivElement) {
// 选择需要观察变动的节点
let targetNode: any = element;
// 观察器的配置(需要观察什么变动)
let config = {
attributes: true,
childList: true,
subtree: true
};
// 当观察到变动时执行的回调函数
const mutationCallback = (mutations: any) => {
for (let mutation of mutations) {
let type = mutation.type;
switch (type) {
case "childList":
console.log("A child node has been added or removed.");
break;
case "attributes":
console.log(`The ${mutation.attributeName} attribute was modified.`);
console.log(mutation.attributeName)
break;
case "subtree":
console.log(`The subtree was modified.`);
break;
default:
break;
}
}
};
// 创建一个观察器实例并传入回调函数
let observer = new MutationObserver(mutationCallback);
console.log(observer)
// 以上述配置开始观察目标节点
observer.observe(targetNode, config);
// observer.disconnect();
}
function Map() {
// 获取dom元素
const mapRef: MutableRefObject<any> = useRef();
useEffect(() => {
// 给dom元素增加监听事件
addWatch(mapRef.current)
});
return (
<div className='form_box' ref={mapRef}>
<div id='ol_map'></div>
</div>
);
}
export default Map;