3.2 Updating the Rendered Element 更新被渲染的元素

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元素是不可变得。你但你创建了元素,你就不能改变他的子集和属性。元素就像在电影里单独的帧:它代表不同时间点的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().

据我所知,更新UI的唯一方法就是创建一个新的元素并且把它粘贴到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()回调函数每隔一秒调用一次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.
注意
实际上,大多数React应用只会调用一次ReactDOM.render()。在接下来的章节中,我们将学习如何将这些代码封装到有状态的组件中。
我们建议您不要跳过本主题,因为它们彼此之间存在关联。


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容