使用@ React-Google-Maps / api将HTML渲染到Infowindow中

问题描述 投票:0回答:1

如何在Google Maps Infowindow中呈现HTML?

我尝试了几种不同的方法来执行此操作,但是似乎没有一种有效。

我的代码:

import React, { Component, useState } from 'react';
import ReactDOMServer from 'react-dom/server';
import { GoogleMap, LoadScript, useLoadScript, InfoWindow, Marker, } from '@react-google-maps/api'

export class MarkerWithInfoWindow extends React.Component {

    constructor() {
        super();
        this.state = {
            isOpen: false
        }
        this.onToggleOpen = this.onToggleOpen.bind(this);
        this.onEventWindowClick = this.onEventWindowClick.bind(this)
    }

    onToggleOpen() {
        this.setState({
            isOpen: !this.state.isOpen
        });
    }



    render() {

        const imgUrl = this.props.icon;
        return (<Marker
            title={this.props.title}
            position={this.props.position}

            icon={{
                url: imgUrl,
            }}
        >
            {this.state.isOpen && <InfoWindow
                onCloseClick={this.onToggleOpen}
                position={this.props.position}
                onMouseOut={this.onToggleOpen}
                pixelOffset={{ width: 25, height: 25 }}
                zIndex={-1}
                onClick={this.onEventWindowClick(this)} 
            >
                <> {ReactDOMServer.renderToString(this.props.content)}</>
            </InfoWindow>}
        </Marker>)
    }
}

我的结果看起来像这样:

enter image description here

html reactjs google-maps infowindow
1个回答
0
投票

我想content道具用HTML字符串表示,然后需要将dangerouslySetInnerHTML设置为将其呈现为html,而不是将其返回为纯字符串,例如:

dangerouslySetInnerHTML

用法

const InfoWindowContent = () => <div dangerouslySetInnerHTML={{ __html: this.props.content }}></div>;

<InfoWindow onCloseClick={this.onToggleOpen} position={this.props.position}> <InfoWindowContent/> </InfoWindow>

© www.soinside.com 2019 - 2024. All rights reserved.