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

后端 未结 2 438
忘掉有多难
忘掉有多难 2020-12-10 12:30

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:

2条回答
  •  北海茫月
    2020-12-10 12:45

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

    1 2 3

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

    1{" "} 2{" "} 3

    …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):

    1 2 3

    …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")
    );
    

提交回复
热议问题