React.js 中的渲染元素


React 应用程序中最小型的构建块是元素。元素示例如下 -

const message = <h1>Welcome, Steve</h1>;

React DOM 使用转换后的 react 元素更新实际 DOM。React 组件由元素组成。

在 DOM 中渲染元素

主 html 文件中将有一个父 div 元素。此 div 可称为 root。

<div id=”app”> </div>

如果需要,ReactDOM 可管理应用程序 div 中的所有内容。可以在应用程序中添加多个此类隔离 div。

要渲染元素,它将传给 ReactDOM 渲染方法 -

const message = <h1>Welcome, Steve</h1>;
ReactDOM.render(message, document.getElementById('app'));

这将在浏览器上显示消息 - 欢迎,Steve

React 元素是不可变的,这意味着它一旦创建就无法更改。更改将创建一个新元素并更新 UI。

显示当前时间 

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

示例

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
function getCurrentTime() {
   const currentTime = (
      <div>
         <h1>Welcome !</h1>
         <h2>It is {new Date().toLocaleTimeString()}.</h2>
      </div>
   );
   ReactDOM.render(currentTime, document.getElementById('root'));
}
setInterval(getCurrentTime, 1000);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

输出

更新时间: 2019-08-28

665 次观看

开启你的职业生涯

完成课程,获得认证

开始学习
广告