使用 leaflet 1.7.1
、react 17.0.2
、react-leaflet 3.1.0
。
我正在尝试从 this discussion 开始并使用 createControlComponent()
函数在 React 项目中创建自定义 Leaflet 控件。
所以在我的 MyControl.js
文件中我有:
import { createControlComponent } from '@react-leaflet/core'
import ownStyles from '../style/MyControl.module.css'
import { Container } from 'react-bootstrap'
import L from 'leaflet'
L.MyControl = L.Control.extend({
onAdd: function (map) {
return (
<Container classname={ownStyles.mainContainer}>
My container!
</Container>
)
},onRemove: function (map) {}
})
export const MyControl = createControlComponent(
(props) => new L.MyControl(props)
)
我在 App.js
中使用它:
import { MyControl } from './components/MyControl'
import { MapContainer } from 'react-leaflet'
<MapContainer>
<MyControl />
</MapContainer>
此配置返回错误 Uncaught TypeError: el.classname is undefined
。
我尝试在标签 classname
和 <MyControl />
之间添加/删除 <Container />
属性,但没有成功。
发现的一个不受欢迎的解决方案是不在 Leaflet 控件中使用 React 组件,即:
(...)
onAdd: function (map) {
const retDiv = L.DomUtil.create('div')
retDiv.innerHTML = 'A DIV THAT WORKS!'
return retDiv
},(...)
所以看起来'自定义Leaflet控件中的React组件'的配置存在不兼容。
我错过了什么吗?有什么解决方法吗?
还是我们必须使用 L.DomUtil
对象来构建自定义 Leaflet 控件?