自学React从入门到精通,从使用到写源码
|—— README.md ⽂档 |—— public 静态资源 | |—— favicon.ico | |—— index.html | |—— manifest.json |—— src 源码 |—— |—— App.css |—— App.js 根组件 |—— App.test.js |—— index.css 全局样式 |—— index.js ⼊⼝⽂件 |—— logo.svg |—— serviceWorker.js pwa⽀持 |—— package.json npm 依赖
env.js⽤来处理.env⽂件中配置的环境变量
// node运⾏环境:development、production、test等
const NODE_ENV = process.env.NODE_ENV;
// 要扫描的⽂件名数组
var dotenvFiles = [
`${
paths.dotenv}.${
NODE_ENV}.local`, // .env.development.local
`${
paths.dotenv}.${
NODE_ENV}`, // .env.development
NODE_ENV !== 'test' && `${
paths.dotenv}.local`, // .env.local
paths.dotenv, // .env
].filter(Boolean);
// 从.env*⽂件加载环境变量
dotenvFiles.forEach(dotenvFile => {
if (fs.existsSync(dotenvFile)) {
require('dotenv-expand')(
require('dotenv').config({
path: dotenvFile,
})
);
}
});
实践⼀下,修改⼀下默认端⼝号,创建.env⽂件
PORT=8080
webpack.config.js 是webpack配置⽂件,开头的常量声明可以看
出cra能够⽀持ts、sass及css模块化
// Check if TypeScript is setup
const useTypeScript =
fs.existsSync(paths.appTsConfig);
// style files regexes
const cssRegex = /\.css$/;
const cssModuleRegex = /\.module\.css$/;
const sassRegex = /\.(scss|sass)$/;
const sassModuleRegex = /\.module\.(scss|sass)$/;
删除src下⾯所有代码,新建index.js
import React from 'react';
import ReactDOM from 'react-dom';
// 这⾥怎么没有出现React字眼?
// JSX => React.createElement(...)
ReactDOM.render(<h1>Hello React</h1>, document.querySelector('#root'));
React负责逻辑控制,数据 -> VDOM
ReactDom渲染实际DOM,VDOM -> DOM
React使⽤JSX来描述UI
⼊⼝⽂件定义,webpack.config.js
entry: [
// WebpackDevServer客户端,它实现开发时热更新功能
isEnvDevelopment && require.resolve('react-dev-utils/webpackHotDevClient'),
// 应⽤程序⼊⼝:src/index
paths.appIndexJs,
].filter(Boolean),
JSX是⼀种JavaScript的语法扩展,其格式⽐较像模版语⾔,但事实
上完全是在JavaScript内部实现的。
JSX可以很好地描述UI,能够有效提⾼开发效率,体验JSX
JSX实质就是React.createElement的调⽤,最终的结果是
React“元素”(JavaScript对象)。
const jsx = react study
;
ReactDOM.render(jsx,document.getElementById('root'));
表达式{}的使⽤,index.js
const name = "react study";
const jsx = <h2>{
name}</h2>;
函数也是合法表达式,index.js
const user = {
firstName: "tom", lastName: "jerry"};
function formatName(user) {
return user.firstName + " " + user.lastName;
}
const jsx = <h2>{
formatName(user)}</h2>;
jsx是js对象,也是合法表达式,index.js
const greet = <p>hello, Jerry</p>
const jsx = <h2>{
greet}</h2>;
条件语句可以基于上⾯结论实现,index.js
const showTitle = true;
const title = name ? <h2>{
name}</h2> : null;
const jsx = (
<div>
{
/* 条件语句 */}
{
title}
</div>
)