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

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.

主站蜘蛛池模板: 安塞县| 陆丰市| 温州市| 峨山| 汾西县| 连江县| 定襄县| 寻甸| 介休市| 凯里市| 德惠市| 延安市| 沁源县| 施秉县| 龙井市| 合山市| 健康| 武穴市| 潮安县| 历史| 团风县| 精河县| 虎林市| 双江| 东海县| 南木林县| 九江县| 普兰县| 石柱| 临湘市| 安仁县| 凭祥市| 湘阴县| 望江县| 龙江县| 丰城市| 弋阳县| 宜昌市| 盐津县| 泗水县| 睢宁县|