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

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 />
);
主站蜘蛛池模板: 锦屏县| 梁平县| 吕梁市| 大宁县| 台东县| 浪卡子县| 大竹县| 武宣县| 东丰县| 玉溪市| 高密市| 辽源市| 双桥区| 岳阳县| 平塘县| 呼玛县| 耒阳市| 玉屏| 湟源县| 长岛县| 始兴县| 清水县| 隆化县| 乐平市| 从化市| 咸宁市| 贵州省| 玛曲县| 林芝县| 青神县| 富顺县| 长泰县| 溧阳市| 瑞昌市| 屏东市| 威远县| 富阳市| 灵丘县| 雷山县| 南城县| 金秀|