Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

javascript - React props: Using an HTML entity within JSX dynamic content?

I have a React component, to whose props I want to assign a string that includes both JavaScript variables and HTML entities.

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 "".

Is there a way to get an HTML entity to render unescaped in a JSX dynamic content block being assigned to a React props?

Attempts Made

Tried using a template literal:

<MyPanel title={`${name} &ndash; ${description}`}> ... </MyPanel>

Problem: In the rendered output, the &ndash; is being rendered literally as "&ndash;" instead of as "".


Attempted to construct some simple JSX with no quotes:

<MyPanel title={{name} &ndash; {description}} ... </MyPanel>

Problem: This failed at compile time with a syntax error.


Tried working around the syntax error by wrapping the JSX in a <span /> element:

<MyPanel title={<span>{name} &ndash; {description}</span>} ... </MyPanel>

Problem: This works, but I'd rather avoid the superfluous <span /> element being present in the rendered output.


Tried replacing the HTML entity with a Unicode numeric character reference:

<MyPanel title={name + ' u2013 ' + description} ... </MyPanel>

Problems:

  • 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 a Unexpected string concatenation prefer-template error in my team's JSLint checker; a solution that uses string interpolation instead would be better.
question from:https://stackoverflow.com/questions/65893251/html-special-character-in-react-ternary-conditional

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can avoid the superfluous span with a Fragment:

<MyPanel title={<>{name} &ndash; {description}</>} ... </MyPanel>

This feature was introduced in React 16.2.

See the Documentation


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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...