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

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!

主站蜘蛛池模板: 锦州市| 宝丰县| 庆城县| 南投市| 安康市| 商南县| 临泉县| 西乌珠穆沁旗| 德州市| 洪江市| 宿松县| 宣威市| 鱼台县| 永春县| 吴旗县| 九江市| 金沙县| 公主岭市| 鄯善县| 横峰县| 高雄县| 阳曲县| 平顶山市| 卢龙县| 宝鸡市| 南靖县| 英德市| 南华县| 阿图什市| 龙海市| 福清市| 嘉峪关市| 河曲县| 威宁| 临湘市| 廉江市| 武宁县| 宿松县| 呼伦贝尔市| 奉贤区| 徐汇区|