【问题标题】:React - HTML element inside to stringReact - 内部的 HTML 元素到字符串
【发布时间】:2020-12-03 07:22:32
【问题描述】:

我有一个对象,我想在这个对象中设置一个 html 元素

    {
        titleName: "Indorction",
        heading: 'Welcome to JavaScript',
        iconName: faDotCircle,
        description: [
            `
            Do we even need to introduce `${<p>HTML element</p>}`? It’s one of the most popular programming 
            languages on the planet!
            Ever visited a website that made you think…"Hey, this website is really cool and
            `
        ],
    },

【问题讨论】:

    标签: javascript arrays reactjs string redux


    【解决方案1】:

    我不确定如何标记为重复,但您可以在此处找到答案: Render HTML string as real HTML in a React component

    基本上,您希望将字符串呈现为 HTML,这是一种危险的做法,所以要小心。

    const x = {
            titleName: "Indorction",
            heading: 'Welcome to JavaScript',
            iconName: faDotCircle,
            description: [
                `
                Do we even need to introduce <p>HTML element</p>? It’s one of the most popular programming 
                languages on the planet!
                Ever visited a website that made you think…"Hey, this website is really cool and
                `
            ],
        },
    
    

    在你的渲染函数内部:

    <div dangerouslySetInnerHTML={{ __html: x.description }}></div>
    

    【讨论】:

    • 谢谢你的回答,我只是想给对象文本中的特定单词添加样式,例如,改变一个单词的颜色,也许有选项?
    • 对不起,回答迟了,我想你必须为它创建一个自定义解析器或使用上面的innerHtml。我认为一个合理的解决方案是创建一个具有属性的对象数组,例如:description: [{text: 'Do we even', className: 'red-text'}, {text: 'need to introduce', className: ''}],然后将其映射到跨度列表,例如:&lt;span className={item.className}&gt;{item.text}&gt;&lt;/span&gt;。这将使您能够更好地控制整个过程并且更加安全。
    【解决方案2】:

    JavaScript_Lessons_Objects.js

    {
        titleName: "Indorction",
        heading: 'Welcome to JavaScript',
        iconName: faDotCircle,
        description: [
          `
           Do we even need to introduce <b class="hal">JavaScript</b>? It’s one of the most 
           popular programming languages on the planet!.
          `
       ],
    },
    

    Lesson.jsx

    {ReactHtmlParser(this.props.lesson[this.state.indexDescription]["description"])}
    

    【讨论】:

      猜你喜欢
      • 2019-04-21
      • 2018-09-19
      • 1970-01-01
      • 1970-01-01
      • 2020-07-17
      • 1970-01-01
      • 2013-07-04
      • 2011-03-25
      • 1970-01-01
      相关资源
      最近更新 更多