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

Welcome to ReactDOM

Here's a secret about React--it's a library for creating UIs, but not a library for rendering UIs. In itself, it has no mechanism for rendering a UI to the browser.

Fortunately, the creators of React also have a package called ReactDOM for exactly this purpose. Let's install it and then see how it works.

First, we install it with yarn add react-dom@15.6.1.

Then, require it in index.html in much the same way as React:

<body>
<img src="assets/icon.png" id="test-image"/>
<h1>Hello world!</h1>
<div id="root"></div>
<script src="../node_modules/react/dist/react.js"></script>
<script src="../node_modules/react-dom/dist/react-dom.js"></script>
<script>
console.log(React.createElement('h1', null, 'Hello from react!'));
</script>
</body&gt;

ReactDOM has a function called render, which takes two arguments: the React element to be rendered to the screen (hey, we have that already!), and the HTML element it will be rendered inside.

So, we have the first argument, but not the second. We need something in our existing HTML we can grab and hook into; ReactDOM will inject our React element inside of it.

So, below our existing <h1> tag, create an empty div with the ID root.

Then, in our ReactDOM.render function, we’ll pass in the React element, and then use document.getElementById to grab our new div.

Here's what our index.html should look like:

<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
<link rel="stylesheet" href="assets/app.css">
<link rel="shortcut icon" href="assets/favicon.ico" type="image/x-icon">
</head>
<body>
<img src="assets/icon.png" id="test-image"/>
<h1>Hello world!</h1>
<div id="root"></div>
<script src="../node_modules/react/dist/react.js"></script>
<script src="../node_modules/react-dom/dist/react-dom.js"></script>
<script>
ReactDOM.render(React.createElement('h1', null, 'Hello from react!'),
document.getElementById('root'));

</script>
</body>
</html>

Reload the page, and you should see 'Hello from React!' text in the middle of the screen!

主站蜘蛛池模板: 双桥区| 仁怀市| 南城县| 天气| 罗田县| 岳普湖县| 嘉义市| 离岛区| 错那县| 伽师县| 乐平市| 庄河市| 广西| 进贤县| 阳山县| 乌鲁木齐县| 青龙| 水富县| 大冶市| 离岛区| 合水县| 井冈山市| 万源市| 江城| 托克托县| 扬州市| 临邑县| 吉水县| 乐清市| 岳阳市| 湘西| 宜良县| 武乡县| 元氏县| 花莲县| 离岛区| 大冶市| 铁力市| 民权县| 泾阳县| 丰县|