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

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.

主站蜘蛛池模板: 乌鲁木齐市| 灵川县| 沙雅县| 郴州市| 莱芜市| 芮城县| 库伦旗| 师宗县| 信阳市| 峨边| 上犹县| 沈阳市| 佛冈县| 宽城| 罗源县| 宝丰县| 大竹县| 临安市| 湘阴县| 洛隆县| 桃园县| 阆中市| 承德县| 漠河县| 扶余县| 台州市| 湖州市| 赫章县| 丰镇市| 绥宁县| 深水埗区| 东平县| 塔河县| 元氏县| 佛坪县| 黄龙县| 阳曲县| 盐源县| 雅江县| 咸丰县| 科技|