使用react脚手架来创建项目(使用create-react-app创建react应用)

搭建react脚手架

  1. 打开命令行下载脚手架库
npm install -g create-react-app	
  1. 切换到需要创建项目的地址(如需在桌面创建,则先cd desktop)
  2. 创建项目(例创建项目名为hello-react的项目)
create-react-app hello-react

4)启动项目

npm start

基本项目结构

在这里插入图片描述

一个简单的例子,了解每个文件的基本内容

  1. public----->index.html(主要是为了放一个root容器)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>React脚手架</title>
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
</head>
<body>
    <div id="root"></div>
</body>
</html>
  1. src------> App.js(外壳容器,用来放置子组件)
/* 
    此处的Component不是解构赋值,是使用了分别暴露,
    在react中Component从React身上取出来了,然后暴露出来就不用React.Component了 
*/
// 外壳组件
import React,{
    
    Component} from 'react'
import Hello from './components/Hello'
import Welcome from './components/Welcome'
// 创建并暴露App外壳组件
export default class App extends Component{
    
    
    render(){
    
    
        return(
            <div>
                <Hello/>
                <Welcome/>
            </div>
        )
    }
}
  1. src------> index.js(项目的入口文件,把App组件渲染到页面)
// 入口文件
// 引入React核心库
import React from "react";
// 引入ReactDOM
import ReactDOM from 'react-dom'
// 引入App组件
import App from './App'

// 渲染App到页面
ReactDOM.render(<App/>,document.getElementById('root'))
  1. src------->components(用来放置子组件)
    例:Hello组件(文件夹)
    index.jsx
import React,{
    
    Component} from "react";
import './index.css'
export default class Hello extends Component{
    
    
    render(){
    
    
        return(
            <div>
                <h2 className="title">hello,react</h2>
            </div>
        )
    }
}

index.css

.title{
    
    
    background-color: orange;
}

补充

安装react插件,使用rcc可以直接出现类似组件的代码模板
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_48952990/article/details/126369148