openlayers中渲染弹窗到地图上(overlay)

在JavaScript文件中(由于需求原因加载暗系地图风格,所以地图选择了高德,雀氏很方便)

可以根据个人喜好去封装方法,上代码(这个是高德地图添加弹窗,之前写的不严谨)

    //信息窗口
    static infoWindow(animalMarker, item, name) {
        const content = document.createElement("div");
        //创造infowindow实例
        const infoWindow = new AMap.InfoWindow({
            isCustom: true, //使用自定义窗口
            content: content, // 这里可能需要的是原生DOM,不是虚拟DOM,所以不能用react写的组件
            offset: new AMap.Pixel(16, 10),
        });
        ReactDOM.render(<FloatInfoWindow data={item} name={name} />, content); // 把虚拟DOM挂载到原生DOM上
        infoWindow.open(GdMap.map, animalMarker.getPosition());
        return infoWindow;
    }

在js这里是直接通过ReactDOM.render()直接渲染组件

效果图:

 在TypeScript中(openlayers)

封装的代码如下:

    //添加弹窗
    static addInfoOverlay(params) {
        const { data, lnglat, refresh } = params
        const info = document.createElement('div')
        const infoWindow = new Overlay({
            id: data.id,
            element: info,
            positioning: 'bottom-center',       //相对于其位置属性的实际位置
            stopEvent: false,                   //事件冒泡
            offset: [0, -20]
        })
        // this.map.getOverlayById(id)
        const element = React.createElement(InfoWin, { data: data, refresh: refresh });
        const root = ReactDOM.createRoot(
            info
        )
        root.render(element);
        // ReactDOM.render(<InfoWin data={ data } refresh = { refresh } />, info);
        infoWindow.setPosition(lnglat)
        // infoWindow.setPosition(undefined)
        if (!this.map.getOverlayById(data.id)) {
            this.map.addOverlay(infoWindow)
            setTimeout(() => {
                this.map.removeOverlay(infoWindow)
            }, 5000)
        }

        // this.map.removeOverlay(infoWindow)

    }

在使用ReactDOM.render直接渲染组件时无法直接渲染,会报错(具体是什么我忘记了)

需要先React.createElement(InfoWin,{ data: data, refresh: refresh })创建react元素

第一个参数是必填,传入的是似HTML标签名称,eg: ul, li
第二个参数是选填,表示的是属性,eg: className
第三个参数是选填,   子节点,eg: 要显示的文本内容

InfoWin是一个已经封装好的函数组件(弹窗)

然后通过ReactDOM.createRoot().render()的方式渲染到页面上

效果图:

注:ReactDOM.createRoot作为新的rootAPI,它可以在 React 18 中创建一个 root,并支持 React 18 中支持的所有新特性。

详情可参考大佬文章:https://mp.weixin.qq.com/s/2rw7Ztaxdm7WgqaBieDVXg

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值