项目搭建

65 阅读1分钟

next

npx create-next-app@latest

create-react-app

npx create-react-app react-app

两种方式没有好坏区分, 官方目前主推的是next方式, 在此之前主推的是create-react-app, 个人觉得后者的结构更简洁。

结构

├── README.md
├── package-lock.json
├── package.json
├── public
|  ├── favicon.ico
|  ├── index.html
|  ├── logo192.png
|  ├── logo512.png
|  ├── manifest.json
|  └── robots.txt
└── src
   ├── App.css
   ├── App.js
   ├── App.test.js
   ├── index.css
   ├── index.js
   ├── logo.svg
   ├── reportWebVitals.js
   └── setupTests.js

只需要关注两个文件, 入口文件/src/index.js和第一个组件/src/App.js,

入口文件

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

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
reportWebVitals();

首选引入的reactreact-demo有什么区别?

简单的说, react负责描述特性数据, react-demo 负责渲染实现。这样做的好处就是, 当把react-demo 换成 react-native时就是另一种渲染。

reportWebVitals

reportWebVitals.js打开后会发现里面主要是用来抓取用户的一些行为

const reportWebVitals = onPerfEntry => {
  if (onPerfEntry && onPerfEntry instanceof Function) {
    import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
      getCLS(onPerfEntry);
      getFID(onPerfEntry);
      getFCP(onPerfEntry);
      getLCP(onPerfEntry);
      getTTFB(onPerfEntry);
    });
  }
};

export default reportWebVitals;

createRoot

const root = ReactDOM.createRoot(document.getElementById('root'));

创建了一个React根组件,并将其挂载到HTML页面中id为"root"的元素上。使用ReactDOM.createRoot()方法可以创建一个支持React 18新特性的根组件,替代了之前的ReactDOM.render()方法。

root.render

root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

React.StrictMode 组件不用关注, 主要是用来检测告警

上面的代码作用是调用root.render()方法,将App组件渲染到浏览器中。