React elements are immutable. Once you create an element, you can't change its children or attributes. An element is like a single frame in a movie: it represents the UI at a certain point in time.
React元素是不可變得。你但你創(chuàng)建了元素堰怨,你就不能改變他的子集和屬性嫩絮。元素就像在電影里單獨的幀:它代表不同時間點的UI侈询。
With our knowledge so far, the only way to update the UI is to create a new element, and pass it to ReactDOM.render().
據(jù)我所知茫孔,更新UI的唯一方法就是創(chuàng)建一個新的元素并且把它粘貼到ReactDOM.render()里缀雳。
Consider this ticking clock example:
考慮這個滴答作響的時鐘示例:
function tick() {
const element = (
<div>
<h1>Hello, world!</h1>
<h2>It is {new Date().toLocaleTimeString()}.</h2>
</div>
);
ReactDOM.render(
? ?element,
? ?document.getElementById('root')
?);
}
setInterval(tick, 1000);
Try it on CodePen.
在CodePen上嘗試一下贤斜。
It calls ReactDOM.render() every second from a setInterval() callback.
它通過一個setInterval()回調(diào)函數(shù)每隔一秒調(diào)用一次ReactDOM.render()懂酱。
Note:
In practice, most React apps only call ReactDOM.render() once. In the next sections we will learn how such code gets encapsulated into stateful components.
We recommend that you don't skip topics because they build on each other.
注意:
實際上,大多數(shù)React應用只會調(diào)用一次ReactDOM.render()茄猫。在接下來的章節(jié)中狈蚤,我們將學習如何將這些代碼封裝到有狀態(tài)的組件中。
我們建議您不要跳過本主題划纽,因為它們彼此之間存在關(guān)聯(lián)脆侮。