1、脚手架创建启动
切换到想创项目的目录,使用命令:create-react-app hello-react
进入项目文件夹:cd 文件名
启动项目:yarn start
2、脚手架项目结构
public ---- 静态资源文件夹
favicon.icon ------ 网站页签图标
index.html -------- 主页面
logo192.png ------- logo 图
logo512.png ------- logo 图
manifest.json ----- 应用加壳的配置文件
robots.txt -------- 爬虫协议文件
src ---- 源码文件夹
App.css -------- App 组件的样式
App.js --------- App 组件
App.test.js ---- 用于给 App 做测试
index.css ------ 样式
index.js ------- 入口文件
logo.svg ------- logo 图
reportWebVitals.js
--- 页面性能分析文件(需要 web-vitals 库的支持)
setupTests.js
---- 组件单元测试的文件(需要 jest-dom 库的支持)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<!-- %PUBLIC_URL%代表public文件夹的路径 -->
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<!-- 开启理想视口,用于做移动端网页的适配 -->
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- 用于配置浏览器页签+地址栏的颜色(仅支持安卓手机浏览器) -->
<meta name="theme-color" content="red" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<!-- 用于指定网页添加到手机主屏幕后的图标 -->
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!-- 应用加壳时的配置文件 -->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<title>React App</title>
</head>
<body>
<!-- 若llq不支持js则展示标签中的内容 -->
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
3、hello react
//index.js
//引入react核心库
import React from 'react'
//引入ReactDOM
import ReactDOM from 'react-dom'
//引入App组件
import App from './App.jsx'
//渲染App到页面
ReactDOM.render(<App/>,document.getElementById('root'))
//App.jsx
//是不同的暴露方式,{ Component }不是结构赋值,是单独暴露方式
import React, { Component } from 'react'
import Hello from './components/Hello/Hello.jsx'
//暴露App组件
export default class app extends Component {
render() {
return (
<div>
<Hello/>
</div>
)
}
}
//Hello.jsx
import React, { Component } from 'react'
import '../Hello/Hello.css'
export default class Hello extends Component {
render() {
return (
<div>
<h2 className="title">Hello,react</h2>
</div>
)
}
}
//index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<title>React App</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
//Hello.css
.title{
background-color:orange;
}
样式模块化暴露
//Hello.jsx
import React, { Component } from 'react'
import hello from './Hello.module.css'
export default class Hello extends Component {
render() {
return (
<div>
<h2 className={hello.title}>Hello,react</h2>
</div>
)
}
}
//Hello.module.css
.title{
background-color:orange;
}
4、React ajax
- React 本身只关注于界面, 并不包含发送 ajax 请求的代码
- 前端应用需要通过 ajax 请求与后台进行交互(json 数据)
- react 应用中需要集成第三方 ajax 库(或自己封装)