【问题标题】:How to render HTML entity in React without dangerouslySetInnerHTML?如何在没有危险的 SetInnerHTML 的情况下在 React 中呈现 HTML 实体?
【发布时间】:2018-11-29 12:03:52
【问题描述】:

我在我的网站中使用自定义字体,类似于 Font Awesome,具有简单的签名:

<i className="icon-plus"></i>

但我想创建自己的组件,该组件将呈现动态 HTML 实体,例如:

const iconEntity = '&#xf2b9;' // (Font Awesome HTML entity example)
const icon1 = '&#xf13d;' // dynamic entities

class OwnIcon extends React.Component {
  render() {
   return <i>{iconEntity}</i>
  }
}

但这不起作用。阅读此post 后,我尝试使用dangerouslySetInnerHTML 并且它有效,例如:

const iconEntity = '&#xf2b9;'

class OwnIcon extends React.Component {
  render() {
    return <i className="icon" dangerouslySetInnerHTML={{__html: iconEntity }}></i>
  }
}

但这是一个有点丑陋的解决方案。 看了JSX gotchas后发现有这样的解决方案:

A safer alternative is to find the unicode number corresponding to the entity and use it inside of a JavaScript string:

<div>{'First \u00b7 Second'}</div>
<div>{'First ' + String.fromCharCode(183) + ' Second'}</div>

但是我如何转换(例如,Font Awesome)Unicode 私人使用字符"\f007" 或 HTML 十六进制实体&amp;#xf007 以获取 unicode 数字以摆脱 dangerouslySetInnerHTML 并以更“清晰”的方式呈现图标?

文本示例:here

【问题讨论】:

  • 为什么不使用与 FA 相同的系统?使用::before { content: &gt;entity&lt; } 为每个实体创建类并将该类应用于您的&lt;i /&gt; 标记?
  • 出于某种原因,要求迫使我在不使用伪元素的情况下使用此解决方案,因此我正在寻找将其呈现为 HTML 十六进制实体的最佳方法。

标签: html reactjs unicode font-awesome


【解决方案1】:

把它放在Fragment中,这样值就变成了JSX,并且会输出为HTML:

const iconEntity = <Fragment>&#xf2b9;</Fragment>

class OwnIcon extends React.Component {
  render() {
    return <i className="icon">{iconEntity}</i>
  }
}

当然,这样做的缺点是你不能说“让我们变得危险!”比如暗翼鸭。 ;)

【讨论】:

    猜你喜欢
    • 2021-09-30
    • 2016-10-14
    • 2019-04-26
    • 2020-12-02
    • 2018-06-02
    • 1970-01-01
    • 2021-07-24
    • 1970-01-01
    • 2013-06-21
    相关资源
    最近更新 更多