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

Using React

Let's confirm that React is in our project by using it to render a simple element to our screen. This will be our first dipping of our feet into React, so go slow and ensure that you understand each step.

First, we need to import our React package (which we just installed with yarn) into our index.html so that we can use it there.

To do this, we add a <script> tag with the path to the main React file within our node-modules folder. This tag looks like this:

<script src="../node_modules/react/dist/react.js"></script>

Place this in your index.html, at the bottom of the body tag (before the closing </body>).

Okay, we have React! Let's use it to make a simple <h1> tag, just like the one we wrote in HTML.

React has a function called createElement for this purpose. It takes three arguments: element type, something called props (more on that later), and the children (what goes inside the tag).

For us, it looks like this:

React.createElement('h1', null, 'Hello from React!')

This function call creates an element that looks as follows:

<h1>Hello from React!</h1>

To confirm that it will work, let's console.log it out:

<script src="../node_modules/react/dist/react.js"></script>
<script>
console.log(React.createElement('h1', null, 'Hello from react!'))
</script>

Reload index.html, then right-click or control-click and select Inspect to open up DevTools in Chrome and switch to the Console tab. There, we see our element… or not. Instead of the HTML output, we get something like this:

This is not the HTML element we might have expected, but we can see that React has worked in its own way. We have a JavaScript object with a type field of h1. Let’s see whether we can transform this into an actual HTML tag on the screen.

主站蜘蛛池模板: 普兰县| 壶关县| 梅河口市| 祁阳县| 中超| 潼关县| 资兴市| 永修县| 玛纳斯县| 伊吾县| 凉山| 定安县| 二手房| 介休市| 乌拉特中旗| 苗栗市| 墨玉县| 徐州市| SHOW| 定安县| 壶关县| 杭锦旗| 永顺县| 荆门市| 奈曼旗| 黄浦区| 屏东县| 高清| 招远市| 新田县| 临江市| 大庆市| 柳林县| 寿阳县| 夏河县| 阳江市| 五河县| 红桥区| 岱山县| 青铜峡市| 寿光市|