React元素渲染

我们先从index.js文件开始说,先看默认的index.js文件

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

先运行代码,在命令行,进入项目路径:cd hello,运行:npm start
页面效果如下
在这里插入图片描述

  1. 在上面的代码中,
    • 其实这是JSX语法

    • <App />是一个普通的js对象

    • 后面的document.getElementById(‘root’)是获取到的dom元素

    • ReactDOM.render()是渲染函数,将<APP/>渲染到dom元素上

    • 其实上面的代码相当于

      const app = <APP/>
      const root = document.getElementById('root')
      ReactDom.render(app, root)
      
    • 再次运行项目,发现界面不变,说明写法是一致的
      在这里插入图片描述

使用其他元素渲染

修改indexjs文件

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

// JSX语法
// 使用JSX语法可以创建js元素对象
// 注意:JSX元素对象只能有一个根元素
const app = <App />
const h1 = <h1>这是一个h1标签</h1>
const root = document.getElementById('root')
ReactDOM.render(
  h1,
  root
);
reportWebVitals();

运行结果如下
在这里插入图片描述

实现时间的显示

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = document.getElementById('root')
function time() {
  const h1 = <h1>{new Date().toLocaleTimeString()}</h1>
  ReactDOM.render(
    h1,
    root
  );
}
setInterval(time, 1000)

运行项目
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值