【问题标题】:html-to-react: How can I replace all 'img' elements with a React component while preserving styles?html-to-react:如何在保留样式的同时用 React 组件替换所有“img”元素?
【发布时间】:2019-11-28 23:33:51
【问题描述】:

这个问题与html-to-react图书馆有关。

假设我有以下 html 字符串

'<div> <img src="test.png" style="width: 100px;"/> <img src="test2.png" style="margin: 0px 4px;"/> </div>'

通常我会这样解析:

import {Parser} from 'html-to-react'
const reactElement = Parser.parse(htmlString);

这将生成一个 React 元素,其中包含一个 div 和 2 个嵌套的 img 元素作为其子元素。


如何改为解析此字符串,以便将每个 img 替换为自定义 Image 组件,同时保留 img 的原始属性/属性(包括样式)?

例如生成的反应元素将具有以下子元素:

<div> <Image src="test.png" style={{width: 100}}/> <Image src="test2.png" style={{margin: "0px 4px"}}/> </div>

帮助表示赞赏!谢谢

【问题讨论】:

    标签: javascript html css reactjs


    【解决方案1】:

    请试试这个:

    const { Parser } = require('html-to-react');
    
    const htmlString = '<div>
        <img src="test.png" style="width: 100px;"/>
        <img src="test2.png" style="margin: 0px 4px;"/>
    </div>'; 
    
    const reactComponent = Parser.parseWithInstructions(
        htmlString,() {
            return true;
        },[
            {replaceChildren: true}
        ]
    );
    

    【讨论】:

    • 嗨@Aman,你能描述一下这段代码 sn-p 的作用吗?我看不到img 元素在哪里被Image 元素替换。可能我之前没有很好地传达我的问题(我现在向 OP 添加了一些额外的细节)
    猜你喜欢
    • 2013-05-20
    • 1970-01-01
    • 1970-01-01
    • 2017-04-05
    • 2021-04-07
    • 1970-01-01
    • 2020-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多