React props:在 JSX 动态内容中使用 HTML 实体? [英] React props: Using an HTML entity within JSX dynamic content?
问题描述
我有一个 React 组件,它的props 我想分配一个包含 JavaScript 变量和 HTML 实体的字符串.
I have a React component, to whose props I want to assign a string that includes both JavaScript variables and HTML entities.
我尝试过的一些方法导致 HTML 实体被转义.例如,–
被逐字呈现为–
"而不是–
".
Some of the approaches I've attempted have resulted in the HTML entity being rendered escaped. For example, –
gets rendered literally as "–
" instead of as "–
".
有没有办法让 HTML 实体在分配给 React 道具的 JSX 动态内容块中呈现未转义?
Is there a way to get an HTML entity to render unescaped in a JSX dynamic content block being assigned to a React props?
尝试使用模板文字::>
<MyPanel title={`${name} – ${description}`}> ... </MyPanel>
问题:在渲染的输出中,–
被逐字渲染为–
"而不是–
"代码>".
Problem: In the rendered output, the –
is being rendered literally as "–
" instead of as "–
".
尝试构建一些不带引号的简单 JSX:
Attempted to construct some simple JSX with no quotes:
<MyPanel title={{name} – {description}} ... </MyPanel>
问题:编译时由于语法错误而失败.
Problem: This failed at compile time with a syntax error.
尝试通过将 JSX 包装在 <span/>
元素中来解决语法错误:
Tried working around the syntax error by wrapping the JSX in a <span />
element:
<MyPanel title={<span>{name} – {description}</span>} ... </MyPanel>
问题:这可行,但我宁愿避免渲染输出中出现多余的 <span/>
元素.
Problem: This works, but I'd rather avoid the superfluous <span />
element being present in the rendered output.
尝试用 Unicode 数字字符引用替换 HTML 实体:
Tried replacing the HTML entity with a Unicode numeric character reference:
<MyPanel title={name + ' \u2013 ' + description} ... </MyPanel>
问题:
- 这行得通,但(在我看来)使代码少了一点可读.(更明显的是ndash"而不是2013"代表一个破折号字符.)
- 此外,这涉及到
+
-operator 连接,这会在我团队的 JSLint 检查器中触发Unexpected string concatenation preferred-template
错误;使用字符串插值的解决方案会更好.
- This works, but (in my opinion) makes the code a little less readable. (It's more obvious that "ndash" rather than "2013" represents an en-dash character.)
- Also, this involves
+
-operator concatenation, which triggers aUnexpected string concatenation prefer-template
error in my team's JSLint checker; a solution that uses string interpolation instead would be better.
推荐答案
您可以使用 Fragment
避免多余的 span
:
You can avoid the superfluous span
with a Fragment
:
<MyPanel title={<>{name} – {description}</>} ... </MyPanel>
这个特性是在 React 16.2 中引入的.
This feature was introduced in React 16.2.
请参阅文档
我同意 @samanime 的观点,即使用实际字符最适合简单情况,但如果您的内容确实是动态的,我更喜欢使用 Fragment
而不是 entityToChar
或dangerouslySetInnerHTML
方法.
I agree with @samanime that using the actual character is best for simple cases, but if your content is truly dynamic, I would prefer using a Fragment
over either the entityToChar
or dangerouslySetInnerHTML
approaches.
这篇关于React props:在 JSX 动态内容中使用 HTML 实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!