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

后端 未结 2 439
忘掉有多难
忘掉有多难 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...

    <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")
    );
    
    0 讨论(0)
  • 2020-12-10 12:46

    If it's appropriate, you can use display: inline-block with side margin equal to the space width:

    #wrapper span {
      display: inline-block;
      margin-right: 0.28em;
    }
    
    0 讨论(0)
提交回复
热议问题