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
696 views
in Technique[技术] by (71.8m points)

reactjs - How to avoid JSX component from condensing when React.js rendering it?

I find out that React.js will condense JSX component HTML tags when rendering, is it possible to avoid this?

For example, I have a jsx component defined in this way:

<div id="wrapper">
  <span>1</span>
  <span>2</span>
  <span>3</span>
</div>

after rendering, it show up in browser this way, condensed:

<div id="wrapper"><span>1</span><span>2</span><span>3</span></div>

I know it is a bit strange for asking such question, but sometimes I just want the component to be rendered as the way I defined it.

And the difference between condensed and not-condensed code:

not-condensed:

enter image description here

condensed:

enter image description here

They are naturally the same code. Although I know that the not-condensed code acts differently from the condensed one because it contains some tab or blank characters, that is originally how we define it.

Maybe it is ridiculous and makes no sense to do this, but I still appreciate any help, thanks!

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Don’t forget that JSX is just sugar for function calls. So this...

<div id="wrapper">
  <span>1</span>
  <span>2</span>
  <span>3</span>
</div>

...is just sugar for this:

React.createElement("div", { id: "wrapper" },
  React.createElement("span", null, "1"),
  React.createElement("span", null, "2"),
  React.createElement("span", null, "3")
);

If you want whitespace between elements which appear on different lines, you can either add some manually…

<div id="wrapper">
  <span>1</span>{" "}
  <span>2</span>{" "}
  <span>3</span>
</div>

…or open new elements on the same line with whitespace between them (the JSX transpiler respects content between elements, just not linebreaks which are adjacent to elements):

<div id="wrapper">
  <span>1</span> <span>2</span> <span>3</span>
</div>

…both of which transpile to this:

React.createElement("div", { id: "wrapper" },
  React.createElement("span", null, "1"),
  " ",
  React.createElement("span", null, "2"),
  " ",
  React.createElement("span", null, "3")
);

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

...