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

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 />
);
主站蜘蛛池模板: 南开区| 淳安县| 高密市| 通道| 嘉峪关市| 杨浦区| 鲁甸县| 子洲县| 宜州市| 德安县| 隆回县| 丘北县| 封开县| 仲巴县| 泌阳县| 洛川县| 古丈县| 罗源县| 南安市| 永城市| 新和县| 绍兴市| 嘉黎县| 杭锦旗| 辛集市| 耿马| 青阳县| 拉萨市| 抚宁县| 上饶市| 同心县| 七台河市| 雷山县| 荔浦县| 咸宁市| 岳池县| 金寨县| 慈溪市| 嘉义县| 商城县| 喜德县|