React基础目录结构
pubilc
|_ index.html
src
|_ index.js
package.json
yarn.lock
初始化项目: yarn init -y;
安装必要依赖:yarn add react react-dom react-scripts
- src/index.js 中创建第一个小项目
// 引入ReactDOM
import ReactDOM from 'react-dom/client';
// 创建一个jsx
const App = <div>
<h1>这是一个React项目</h1>
<p>终于有了第一个React项目</p>
</div>
// 获取一个根容器
const root = ReactDOM.createRoot(document.getElementById('root'))
// 将App渲染到根容器中
root.render(App)
-
运行
npx react-scripts start预览项目 -
运行
npx react-scripts build打包项目- "Would you like to add the defaults to your pakage.json?(Y/n)" 您想将默认值添加到您的 package.json? 按 Y 确认
-
package.json中添加配置
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build"
},
执行 npm start 等于 npx react-scripts start
执行 npm build 等于 npx react-scripts build
一个简单的列表
src/index.js
// 引入
import ReactDOM from 'react-dom/client'
import './index.css'
const data = [{
id:'001',
month:'四月',
day:'23',
product: '学习vue',
time: '10分钟'
},{
id:'002',
month:'四月',
day:'24',
product: '学习javascript',
time: '10分钟'
},{
id:'003',
month:'四月',
day:'25',
product: '学习css',
time: '10分钟'
},{
id:'004',
month:'四月',
day:'26',
product: '学习react',
time: '10分钟'
}]
const App = <div className='logs'>
{/* 日志项容器 */}
{data.map(item => {
return <div className='item' key={item.id}>
{/* 日志的容器 */}
<div className='date'>
<div className='month'>{item.month}</div>
<div className='day'>{item.day}</div>
</div>
{/* 内容容器 */}
<div className='content'>
<h3>{item.product}</h3>
<div className='time'>{item.time}</div>
</div>
</div>
})}
</div>
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(App)
src/index.css
*{
padding: 0;
margin: 0;
}
body{
background: rgb(252, 238, 130);
}
.item{
display: flex;
background: rgb(255, 213, 75);
margin: 15px;
padding: 10px;
border-radius: 10px;
text-align: center;
align-items: center;
box-shadow: 0 0 8px #a1a2a3;
}
.date{
width: 80px;
height: 80px;
border-radius: 12px;
background: #fff;
}
.month{
background: rgb(255, 64, 64);
line-height: 30px;
border-radius: 12px 12px 0 0;
color: #fff;
}
.day{
line-height: 50px;
font-size: 32px;
}
.content{
flex: 1;
}