我们先从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
页面效果如下
- 在上面的代码中,
-
其实这是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)
运行项目