如何在react-leaflet地图中实现标记Tooltip自动打开?
在react-leaflet中实现Marker自动打开永久Tooltip的方案
嗨,我来帮你搞定这个问题!你在原生Leaflet里实现的永久自动打开Tooltip效果,在react-leaflet里完全可以通过<Tooltip>组件结合对应的props来复刻,具体做法如下:
核心思路
react-leaflet的<Tooltip>组件是对原生Leaflet Tooltip的封装,原生里的配置项大多能直接通过组件props传递。你需要把原来的<Popup>替换(或并存)为<Tooltip>,并设置对应属性来实现永久显示和自动打开。
修改后的完整代码
render() { return ( <div className={'ShapeLayer'}> {this.shapes.map((shape, index) => { return ( <Marker key={shape['id']} position={shape['coordinates']} draggable={false} opacity={1} > {/* 配置Tooltip组件,对应原生的bindTooltip参数 */} <Tooltip permanent={true} className={`shapesText${index}`} offset={[0, 0]} direction="center" > <span>{shape['text']}</span> </Tooltip> {/* 如果需要保留Popup功能,可以继续保留这段代码 */} {/* <Popup> <span>{shape['text']}</span> </Popup> */} </Marker> ); })} </div> ); }
关键属性说明
permanent={true}:对应原生的permanent: true,设置后Tooltip会一直显示,不需要用户触发,也就实现了“自动打开”的效果className={shapesText${index}}:和原生的className一致,用来给每个Tooltip添加自定义样式类offset={[0, 0]}:控制Tooltip相对于Marker的偏移量,和原生配置完全一致direction="center":设置Tooltip的显示方向,这里和原生一样设为居中
备选方案(手动控制打开)
如果因为某些原因permanent属性不满足需求,你也可以通过获取Marker的原生实例手动调用openTooltip()方法,比如在类组件的componentDidMount中处理:
class ShapeLayerComponent extends React.Component { constructor(props) { super(props); this.markerRefs = []; } componentDidMount() { // 遍历所有Marker实例,调用openTooltip this.markerRefs.forEach(ref => { if (ref?.leafletElement) { ref.leafletElement.openTooltip(); } }); } render() { return ( <div className={'ShapeLayer'}> {this.shapes.map((shape, index) => { return ( <Marker ref={el => this.markerRefs.push(el)} key={shape['id']} position={shape['coordinates']} draggable={false} opacity={1} > <Tooltip className={`shapesText${index}`} offset={[0, 0]} direction="center" > <span>{shape['text']}</span> </Tooltip> </Marker> ); })} </div> ); } }
不过一般来说,第一种方案(设置permanent={true})就完全能实现你原生代码里的效果啦。
内容的提问来源于stack exchange,提问作者Stevan Tosic
相关产品推荐
相关产品推荐

