高德地图弹窗AMap.InfoWindow()如何使用react组件作为content

问题介绍

AMap.InfoWindow()用于在地图上弹出详细信息展示窗体。其参数Options中的content属性接受类型为String/HTMLElement,无法直接渲染React组件。你可以查看高德地图API官方文档了解更多信息

解决思路

react-amap是一个基于React封装的高德地图组件库,提供了一种插槽式API,允许将React组件作为InfoWindow的内容。让我们深入了解作者是如何实现的。通过查看github源码,我们可以发现作者是如何创建一个HTML元素作为content,并将React组件渲染到这个div中:

js 复制代码
setChild(props: IWProps) {
    const child = props.children
    if (this.infoDOM && child) {
      render(<div>{child}</div>, this.infoDOM)  // infoDOM: HTMLElement
    } else {
      if (props.children) {
        console.warn('因为你设置 isCustom 为 true,InfoWindow 的 Children 被忽略')
      }
    }
  }

在 React 18 中,render 函数被 createRoot 函数替换,我们直接来看看一个react项目的入口是如何实现渲染的

html 复制代码
//index.html
<!doctype html>
<html lang="en">
  <head>
  ...
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.tsx"></script>
  </body>
</html>
js 复制代码
//main.ts
import ReactDOM from 'react-dom/client'
import App from './App.tsx'

ReactDOM.createRoot(document.getElementById('root')!).render(
  <App />
)

上述代码显示,首先在index.html中创建了一个根节点,然后在main.ts中使用createRoot创建React根元素,最后调用render方法进行渲染。

解决步骤

参考上面的代码,想要在高德地图的InfoWindow中渲染React组件,可以按以下步骤进行:

  1. 创建一个HTML元素:
js 复制代码
const window = document.createElement('div')
  1. 使用ReactDOM.createRoot将React组件渲染到HTML元素中:
js 复制代码
ReactDOM.createRoot(window).render(<YourComponent />)
  1. 使用AMap.InfoWindow(),将之前创建的HTML元素作为content:
js 复制代码
const Window = new AMap.InfoWindow({
  isCustom: true, // 使用自定义窗体
  content: window
})

效果对比

如果我们直接使用React组件效果如下:

js 复制代码
const Window = new AMap.InfoWindow({
  isCustom: true, // 使用自定义窗体
  content: <InfoWindow />
})

而使用上文提供的方法的效果如下:

相关推荐
FrontAI9 小时前
Next.js从入门到实战保姆级教程:环境配置与项目初始化
react.js·typescript·学习方法
用户31532477954512 小时前
React19项目中 FormEdit / FormEditModal 组件封装设计说明
前端·react.js
Ruihong14 小时前
Vue3 转 React:组件透传 Attributes 与 useAttrs 使用详解|VuReact 实战
vue.js·react.js
橘子编程16 小时前
React 19 全栈开发实战指南
前端·react.js·前端框架
弓.长.17 小时前
ReactNative for OpenHarmony项目鸿蒙化三方库:react-native-svg(CAPI) — 矢量图形组件
react native·react.js·harmonyos
局i18 小时前
从零搭建 Vite + React 项目:从环境准备到干净项目的完整指南
前端·react.js·前端框架
Lazy_zheng18 小时前
SDD 实战:用 Claude Code + OpenSpec,把 AI 编程变成“流水线”
前端·react.js·ai编程
光影少年18 小时前
如何实现RN应用的离线功能、数据缓存策略?
react native·react.js·掘金·金石计划
弓.长.19 小时前
ReactNative for OpenHarmony项目鸿蒙化三方库:rn-placeholder — 骨架屏占位组件
react native·react.js·harmonyos
whuhewei20 小时前
React性能优化
前端·react.js·性能优化