String as html in reactjs

主宰稳场 提交于 2019-12-23 09:55:58

问题


I have a function which returns several lines of html, like so:

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 ?


回答1:


While using dangerouslySetInnerHTML does work, I recommend avoiding it in this case since you are in control of the markup. That attribute starts with dangerously for a reason: those badges are now a vector for code injection.

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>
    );
}



回答2:


So I found the answer myself: We need to use dangerouslySetInnerHTML={{__html: badges} to achieve this result.

So:

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

did the trick. Hope it helps.



来源:https://stackoverflow.com/questions/23602974/string-as-html-in-reactjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!