vuepress-theme-vdoing/docs/《React》笔记/01.核心概念/02.元素渲染.md

73 lines
2.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: 元素渲染
date: 2021-03-24 17:56:40
permalink: /pages/b5d372/
categories:
- 《React》笔记
- 核心概念
tags:
- React
author:
name: xugaoyi
link: https://github.com/xugaoyi
---
# 02. 元素渲染
元素是构成 React 应用的最小砖块,描述了你在屏幕上想看到的内容。
```js
const element = <h1>Hello, world</h1>;
```
与浏览器的 DOM 元素不同,**React 元素是创建开销极小的普通对象**。React DOM 会负责更新 DOM 来与 React 元素保持一致。
## 将一个元素渲染为 DOM
假设你的 HTML 文件某处有一个 `<div>`
```html
<div id="root"></div>
```
根节点React应用只有单一根DOM节点
> 但一个html页面可以有多个React应用每个应用对应一个独立根节点。
```jsx
const el = <h1>Hello</h1>
ReactDOM.render(el, document.getElementById('root'))
```
## 更新已渲染的元素
React 元素是[不可变对象](https://en.wikipedia.org/wiki/Immutable_object)。一旦被创建,你就无法更改它的子元素或者属性。一个元素就像电影的单帧:它代表了某个特定时刻的 UI。
根据我们已有的知识,更新 UI 唯一的方式是创建一个全新的元素,并将其传入 [`ReactDOM.render()`](https://zh-hans.reactjs.org/docs/react-dom.html#render)。
考虑一个计时器的例子:
```jsx
function tick() {
// element是一个React元素
const element = (
<div>
<h1>Hello, world!</h1>
<h2>It is {new Date().toLocaleTimeString()}.</h2>
</div>
);
ReactDOM.render(element, document.getElementById('root'));}
setInterval(tick, 1000);
```
注意:在实践中,**大多数 React 应用只会调用一次 [`ReactDOM.render()`](https://zh-hans.reactjs.org/docs/react-dom.html#render)**。在下一个章节,我们将学习如何将这些代码封装到**[有状态组件](https://zh-hans.reactjs.org/docs/state-and-lifecycle.html)**中。
## React 只更新它需要更新的部分
上个例子中,尽管每一秒我们都会新建一个描述整个 UI 树的元素但React DOM **只会更新实际改变了的内**容。