[英]How to render HTML entity in React without dangerouslySetInnerHTML?
I'm using custom fonts in my site, similar to Font Awesome, which have simple signature: 我在网站中使用自定义字体,类似于Font Awesome,它们具有简单的签名:
<i className="icon-plus"></i>
But I want to create own component which will be render dynamic HTML entities like: 但是我想创建自己的组件,该组件将呈现动态HTML实体,例如:
const iconEntity = '' // (Font Awesome HTML entity example)
const icon1 = '' // dynamic entities
class OwnIcon extends React.Component {
render() {
return <i>{iconEntity}</i>
}
}
But this doesn't work. 但这是行不通的。 After reading this post I trier using dangerouslySetInnerHTML
and it works, eg: 看完这篇文章后,我会使用dangerouslySetInnerHTML
使用SetInnerHTML进行dangerouslySetInnerHTML
并且可以正常工作,例如:
const iconEntity = ''
class OwnIcon extends React.Component {
render() {
return <i className="icon" dangerouslySetInnerHTML={{__html: iconEntity }}></i>
}
}
But it's a little bit ugly solution. 但这是一个难看的解决方案。 After reading JSX gotchas I found that there are solutions like: 阅读JSX陷阱后,我发现有一些解决方案,例如:
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>
But how I could convert(for example, Font Awesome) Unicode Private-Use characters "\\f007"
or HTML hex entity 
to get unicode number to get rid of dangerouslySetInnerHTML
and render icons in more "clear" way? 但是,如何转换(例如Font Awesome)Unicode专用字符"\\f007"
或HTML十六进制实体
来获得unicode号以摆脱dangerouslySetInnerHTML

并以更“清晰”的方式呈现图标?
Put it in a Fragment
so the value becomes JSX, and will be output as HTML: 将其放在Fragment
以便该值变为JSX,并将其输出为HTML:
const iconEntity = <Fragment></Fragment>
class OwnIcon extends React.Component {
render() {
return <i className="icon">{iconEntity}</i>
}
}
The downside to this, of course, is that you don't get to say "Let's get dangerous!" 当然,这样做的缺点是您不会说“让我们变得危险!” like Darkwing Duck. 像黑翼鸭一样。 ;) ;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.