在React不直接管理DOM的区域中的浏览器中使用ReactDOMServer.renderToString可以吗? [英] Is it ok to use ReactDOMServer.renderToString in the browser in areas where React isn't directly managing the DOM?
问题描述
我正在使用传单(通过
I'm working on an app using Leaflet (via react-leaflet). Leaflet directly manipulates the DOM. The react-leaflet library doesn't change that, it just gives you React components that you can use to control your Leaflet map in a React-friendly way.
在此应用中,我想使用自定义地图标记,这些标记是包含一些简单元素的div.在Leaflet中执行此操作的方法是在以下位置将标记的icon
属性设置为 DivIcon 您可以设置自定义HTML.您可以通过将DivIcon的html
属性设置为包含HTML的字符串来设置内部HTML.就我而言,我希望从React组件呈现HTML.
In this app, I want to use custom map markers that are divs containing a few simple elements. The way to do that in Leaflet is to set your marker's icon
property to a DivIcon, in which you can set your custom HTML. You set that inner HTML by setting the DivIcon's html
property to a string containing the HTML. In my case, I want that HTML to be rendered from a React component.
为了做到这一点,似乎正确的方法是使用ReactDOMServer.renderToString()
将地图标记内想要的Component渲染为字符串,然后将其设置为DivIcon的html
属性. :
In order to do that, it seems like the correct approach is to use ReactDOMServer.renderToString()
to render the Component that I want inside the map marker into a string, which I would then set as the html
property of the DivIcon:
MyMarker.js:
MyMarker.js:
import React, { Component } from 'react'
import { renderToString } from 'react-dom/server'
import { Marker } from 'react-leaflet'
import { divIcon } from 'leaflet'
import MarkerContents from './MarkerContents'
export class MyMarker extends Component {
render() {
const markerContents = renderToString(<MarkerContents data={this.props.data} />)
const myDivIcon = divIcon({
className: 'my-marker',
html: markerContents
})
return (
<Marker
position={this.props.position}
icon={myDivIcon} />
)
}
}
但是,根据反应文档:
此[renderToString]仅应在服务器上使用.
This [renderToString] should only be used on the server.
这是严格的规定吗?还是仅是说服人们规避ReactDOM对DOM的有效管理?
Is this a strict rule, or is it only meant to dissuade people from circumventing ReactDOM's efficient management of the DOM?
我想不出另一种(更好的)方式来实现我所追求的目标.任何意见或想法将不胜感激.
I can't think of another (better) way to accomplish what I'm after. Any comments or ideas would be greatly appreciated.