问题
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