我目前正在尝试调整React组件,以便可以从常规的非React脚本中调用它。我正在尝试使用的特定组件是“react-responsive-carousel”。
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>然后在“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));
}然后,非React脚本将使用的调用代码:
renderCarousel("root", document.getElementById("slides").innerHTML);这样做的问题是引入了一个额外的'div‘,它破坏了carousel的行为。有没有办法通过这样的方式传递这个HTML ? id为'slides‘的div的内部HTML直接位于Carousel组件之下,或者可能有其他方法来实现预期的目标?
请注意,这需要在ES5调用上下文中工作。
发布于 2018-12-23 09:18:44
我理解这个问题,所以你那里的html应该是所有的幻灯片,对吧?
我要做的是将幻灯片作为数组传递给函数:
renderCarousel(targetElementId, slides)所以你可以这样做:
function renderCarousel(targetElementId, slides=[]) {
const App = function() {
return <Carousel>
{slides.map(html => <div dangerouslySetInnerHTML={{ __html: html }} />)}
</Carousel>;
};
render(<App />, document.getElementById(targetElementId));
}它应该与以下内容一起工作:
const slides = Array.from(document.getElementById("slides").children)
renderCarousel("root", slides.map(slide=> slide.innerHTML))让我知道它进行得怎么样!
https://stackoverflow.com/questions/53900459
复制相似问题