首页 > 解决方案 > 从 JSON 中删除 src 以创建图像

问题描述

我知道这可能以前做过,但我找不到合适的关键字在谷歌上搜索这个。基本上我想要做的是创建一个图像元素来从响应对象做出反应。但是响应对象包含 html 标签,所以我不能直接创建图像。任何人都可以帮助我实现这一目标。这是我要从中显示图像的对象属性

{
 "content": "<img src='https://i.cbc.ca/1.5379524.1575076619!/fileImage/httpImage/image.JPG_gen/derivatives/16x9_460/czech-china.JPG' alt='CZECH-CHINA/' width='460' title='Czech Republic&#39;s President Milos Zeman (R) and his Chinese counterpart Xi Jinping walk past an honour guard at Prague Castle in Prague, Czech Republic, March 29, 2016. ' height='259' /> <p>A half-decade ago, China planted an economic flag in Central Europe with its multi-billion-dollar Belt and Road plan to build a vast infrastructure network. Five years on, though, some of those countries are finding the relationship increasingly uncomfortable.</p>"
}

如何破译此内容以从此处获取文本和图像。正如@Renaldo Balaj 所建议的那样,我尝试使用 html 来响应包,但我仍然得到一个没有在图像或段落中呈现的字符串。这是我的 JSX

<div className="dark-overlay">
        <div className="news">
            <Carousel>
            { news.items.map( news => {
                    const htmlInput = news.content;
                    const htmlToReactParser = new HtmlToReactParser();
                    const reactElement = htmlToReactParser.parse(htmlInput);
                    const reactHtml = ReactDOMServer.renderToStaticMarkup(reactElement);
                    console.log(reactHtml);
                    return <Carousel.Item key={news.guid}>
                         {reactHtml}

                    </Carousel.Item>;
                }
            )}
            </Carousel>
        </div>
    </div>

标签: javascriptreactjs

解决方案


您不需要获取 src,您可以像从后端获取它一样打印 img。

有为这个东西构建的包,比如: react-html-parser (你只需要给出“ <img >”,它就会返回一个完全工作的 img 标签)

我在评论中看到你在实现它时遇到了问题,所以这里是工作演示https ://stackblitz.com/edit/react-ncvxgb?file=index.js


推荐阅读