官术网_书友最值得收藏!

Multi-line

Let's start with a very simple one. As stated previously, one of the main reasons we should prefer JSX over React's createElement function is because of its XML-like syntax, and because balanced opening and closing tags are perfect to represent a tree of nodes.

Therefore, we should try to use it in the right way and get the most out of it.

One example is as follows; whenever we have nested elements, we should always go multiline:

  <div> 
<Header />
<div>
<Main content={...} />
</div>
</div>

This is preferable to the following:

  <div><Header /><div><Main content={...} /></div></div>

The exception is if the children are not elements, such as text or variables. In that case, it makes sense to remain on the same line and avoid adding noise to the markup, as follows:

  <div> 
<Alert>{message}</Alert>
<Button>Close</Button>
</div>

Always remember to wrap your elements inside parentheses when you write them in multiple lines. JSX always gets replaced by functions, and functions written on a new line can give you an unexpected result because of automatic semicolon insertion. Suppose, for example, that you are returning JSX from your render method, which is how you create UIs in React.

The following example works fine because the div element is on the same line as the return:

  return <div />;

The following, however, is not right:

  return 
<div />;

The reason for this is because you would then have the following:

  return; 
React.createElement("div", null);

This is why you have to wrap the statement in parentheses, as follows:

  return ( 
<div />
);
主站蜘蛛池模板: 洛浦县| 大同县| 运城市| 舞钢市| 彝良县| 阿拉尔市| 怀安县| 梨树县| 兴隆县| 潢川县| 靖安县| 探索| 桑日县| 赤水市| 慈利县| 海宁市| 南漳县| 鹿泉市| 于田县| 丹阳市| 桓仁| 雷波县| 张家港市| 罗平县| 石棉县| 开鲁县| 确山县| 阿瓦提县| 垣曲县| 长兴县| 舞钢市| 赤壁市| 大荔县| 固安县| 海伦市| 清流县| 诏安县| 洞头县| 盐山县| 黄浦区| 乳源|