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

Our first ES6

Let’s open up our src/index.js and see how we can spice it up.

First, we can replace our require calls with the new import syntax. It looks like this:

import React from ‘react’;
import ReactDOM from 'react-dom';

It's a little cleaner, and it lets us do some cool stuff, which we’ll see later.

Do that for both React and ReactDOM, and then we can finally replace our React.createElement call.

As you may guess, it would be very unwieldy to build a complex UI by calling React.createElement for every HTML element we need. We want the power and functionality of JavaScript, but with the readability of HTML.

Enter JSX; JSX is a type of syntax that looks like HTML, but is actually JavaScript underneath. In other words, it compiles down to React.createElement, just as our ES6 JavaScript will compile into ES5.

It has some gotchas as well, since it’s not true HTML, but we’ll get there. The last thing to note is that JSX makes some developers very uncomfortable; they say it looks odd to have HTML inside JavaScript. I don’t agree, personally, but it's an opinion thing. Whatever your aesthetic stance, JSX offers a lot of convenience, so let’s try it out.

We can simply convert our line of code to this:

ReactDOM.render(<h1>Hello from ES6!</h1>, document.getElementById('root'));

Run yarn start (or, if it’s already running, it should automatically refresh). If Babel is working correctly, nothing should change. Our first JSX is done!

We will, of course, work much more with JSX, looking at how it differs from HTML, and what advantages it offers to us as developers. However, for now, let’s make our lives even easier.

主站蜘蛛池模板: 阿合奇县| 平原县| 葵青区| 常宁市| 濮阳市| 泗洪县| 高要市| 肃北| 海口市| 晋宁县| 开封市| 余干县| 平凉市| 罗平县| 临桂县| 兴城市| 凤翔县| 龙口市| 子洲县| 商都县| 潍坊市| 葫芦岛市| 新巴尔虎左旗| 昌都县| 岗巴县| 大石桥市| 洛川县| 阿勒泰市| 五家渠市| 绥芬河市| 奉化市| 吉水县| 长顺县| 万安县| 松阳县| 股票| 峨边| 吐鲁番市| 开化县| 五河县| 开原市|