简体   繁体   English

在没有div的情况下使用React的危险SetInnerHTML吗?

[英]Using React's dangerouslySetInnerHTML without the div?

I am currently trying to adapt a React component so that it can be called from a regular non-React script. 我目前正在尝试修改React组件,以便可以从常规的非React脚本中调用它。 The particular component I am trying to get working is ' react-responsive-carousel '. 我正在尝试使用的特定组件是“ react- response-carousel ”。

The HTML: HTML:

<div id="slides" style="display: none">
    <div>
      <img src="http://lorempixel.com/output/cats-q-c-640-480-1.jpg" />
      <p className="legend">Legend 1</p>
    </div>
    <div>
      <img src="http://lorempixel.com/output/cats-q-c-640-480-2.jpg" />
      <p className="legend">Legend 2</p>
    </div>
<div>

<div id="root"></div>

Then in the 'react adaptor': 然后在“反应适配器”中:

import "react-responsive-carousel/lib/styles/carousel.min.css";
import { Carousel } from "react-responsive-carousel";

function renderCarousel(targetElementId, html) {
  const App = function() {
    return <Carousel>
      <div dangerouslySetInnerHTML={{ __html: html }} />
    </Carousel>;
  };

  render(<App />, document.getElementById(targetElementId));
}

Then the calling code that would be used by the non-React script: 然后非反应脚本将使用的调用代码:

renderCarousel("root", document.getElementById("slides").innerHTML);

The issue with this is that an extra 'div' is introduced which breaks the carousel's behaviour. 问题是引入了一个额外的“ div”,它破坏了轮播的行为。 Is there any way I can pass this HTML in such a way the inner HTML of div with id 'slides' is directly under the Carousel component or maybe there is another way of achieving the intended goal? 有什么方法可以通过这种方式传递此HTML,即具有id'slides'的div的内部HTML直接位于Carousel组件的下面,或者还有另一种实现预期目标的方法?

Note, this needs to work from an ES5 calling context. 注意,这需要在ES5调用上下文中进行。

I understood the issue, so the html you have there, would be all the slides right ? 我了解这个问题,因此您那里的html会正确显示所有幻灯片吗?

What I would do is to pass the slides to the function as an array: 我要做的是将幻灯片作为数组传递给函数:

renderCarousel(targetElementId, slides)

so you can do something like: 因此您可以执行以下操作:

function renderCarousel(targetElementId, slides=[]) {
  const App = function() {
    return <Carousel>
      {slides.map(html => <div dangerouslySetInnerHTML={{ __html: html }} />)}
    </Carousel>;
  };

  render(<App />, document.getElementById(targetElementId));
}

it should work with something like: 它应该与类似的东西一起工作:

const slides = Array.from(document.getElementById("slides").children)
renderCarousel("root", slides.map(slide=> slide.innerHTML))

Let me know how it goes ! 让我知道事情的后续 !

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM