简体   繁体   English

在reactjs中将字符串作为html

[英]String as html in reactjs

I have a function which returns several lines of html, like so: 我有一个函数,它返回几行html,如下所示:

render: function() {
  var badges = user.get('achievements').badges.map(function(badge) {
    var str = '<h3><span className="fa fa-fw '

    switch(badge.id) {
    case '0':
      str += ('fa-briefcase"></span><small>' + badge.text + '</small></h3>')
      break;
    case '1':
      str += ('fa-shopping-cart"></span><small>' + badge.text + '</small></h3>')
      break;
    ...
    }

    return str;
  });

  return (
    <div className="pull-right">
      {badges}
    </div>
  );
}

On doing this the string is rendered as it is on the page, as text: 这样做时,字符串将以文本形式呈现在页面上:

<h3><span className="fa fa-fw fa-briefcase"></span><small>Visionary</small></h3><h3><span className="fa fa-fw fa-shopping-cart"></span><small>Active</small></h3><h3><span className="fa fa-fw fa-sitemap"></span><small>Lorem</small></h3><h3><span className="fa fa-fw fa-tasks"></span><small>Ipsum</small></h3><h3><span className="fa fa-fw fa-signal"></span><small>Dolor</small></h3><h3><span className="fa fa-fw fa-check-square"></span><small>Amet;</small></h3>

How do I render it as proper HTML ? 如何将其呈现为适当的HTML?

While using dangerouslySetInnerHTML does work, I recommend avoiding it in this case since you are in control of the markup. 当使用dangerouslySetInnerHTML确实可以工作时,由于您可以控制标记,因此建议在这种情况下避免使用它。 That attribute starts with dangerously for a reason: those badges are now a vector for code injection. 该属性以dangerously开头是有原因的:这些徽章现在是代码注入的向量。

render() {
    const BADGE_ID_TO_ICON_CLASS_NAME = {
      '0': 'fa-briefcase',
      '1': 'fa-shopping-cart',
      ...
    };

    return (
      <div className="pull-right">
        {user.get('achievements').badges.map(badge => (
          <h3 key={badge.id}>
            <span
              className={`fa fa-fw ${BADGE_ID_TO_ICON_CLASS_NAME[badge.id]}`}
            />
            <small>{badge.text}</small>
          </h3>
        ))}
      </div>
    );
}

So I found the answer myself: We need to use dangerouslySetInnerHTML={{__html: badges} to achieve this result. 因此,我自己找到了答案:我们需要使用dangerouslySetInnerHTML={{__html: badges}来获得此结果。

So: 所以:

<div className="pull-right" dangerouslySetInnerHTML={{__html: badges}}></div>

did the trick. 做到了。 Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM