在React不直接管理DOM的区域中的浏览器中使用ReactDOMServer.renderToString可以吗? [英] Is it ok to use ReactDOMServer.renderToString in the browser in areas where React isn't directly managing the DOM?

查看:368
本文介绍了在React不直接管理DOM的区域中的浏览器中使用ReactDOMServer.renderToString可以吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用传单(通过

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.

推荐答案

根据新文档:

在服务器和浏览器中都可以使用以下方法 环境:

The following methods can be used in both the server and browser environments:

  • renderToString()
  • renderToStaticMarkup()

这篇关于在React不直接管理DOM的区域中的浏览器中使用ReactDOMServer.renderToString可以吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆