React 快速上手 - 03 腳手架建立項目 一切都是組件

reactjs

目錄

React 快速上手 - 03 腳手架建立項目 一切都是組件

目標

  • 經過腳手架建立項目
  • 運行項目
  • 告終項目結構
  • 動手建立組件

建立項目

我推薦用腳手架做爲開始,剛開始學習時一開始就搗騰 Webpack Babel 本身配置運行環境,而後你會發現一堆知識要補充,再而後就忘記了我一開始只是爲了跑個 React。css

本文討論的都是基於 npm 構建的環境,若是直接在瀏覽器中運行,須要用 es5 直接寫,否者會遇到兼容問題。html

下面開始咱們的正題!前端

1. 安裝腳手架

cnpm install -g create-react-app

關於 npm 加速 問題,請查看上篇react

2. 執行腳手架程序

cd ~/Documents/labs
create-react-app reactjs-example

我專門建了個 labs 目錄,用來測試各類程序,這樣不會把你的磁盤目錄弄得很凌亂git

錄像es6

create-react-app

3. 運行項目

cd reactjs-example
npm start

錄像github

create-react-app-run

瀏覽器打開 http://localhost:3000/npm

create-react-app-page

看到這個乾淨的頁面,你們能夠放心了,環境一切正常json

目錄結構

.
├── README.md                                 | 幫助說明
├── build                                     | 發佈目錄
├── package.json                              | npm包管理
├── public                                    | 首頁模板
│   ├── favicon.ico
│   ├── index.html
│   └── manifest.json
├── src                                       | 源碼
│   ├── App.css
│   ├── App.js
│   ├── App.test.js
│   ├── index.css
│   ├── index.js
│   ├── logo.svg
│   └── registerServiceWorker.js

咱們大部份內容都是在 src 下完成redux

寫個簡單的做爲開始

編輯 app.js 文件

import React, {Component} from 'react'
const Element1 = () => <h2>組件1 - 常量</h2>
export default Element1

輸出: 組件1 - 常量

就3行,你們能夠本身動手試下

能做爲組件的js對象,大體以下幾種:

1. 常量組件

const Element1 = () => <h2>組件1 - 常量</h2>

2. 變量組件

let Element2 = () => <h2>組件2 - 變量</h2>

3. es5 函數組件

function Element3() {
  return <h2>組件3 - es5 函數</h2>
}

4. es6 箭頭函數組件

let Element4 = () => {
  return <h2>組件4 - es6 箭頭函數</h2>
}

5. React.Component 類組件

class Element5 extends Component {
  render() {
    return <h2>組件5 - React.Component 類對象</h2>
  }
}

es6類 不是組件 重要!

class Element6 {
  render() {
    return <h2>組件6 - es6 class 類對象</h2>
  }
}

運行後報錯!

std-class-not-as-component

使用 codepen 調試代碼

codepen.io 是一個不錯的在線調試代碼平臺,個人 codepen.io/ducafecat/

本文代碼 codepen

https://codepen.io/ducafecat/...

項目編譯

  • 運行編譯
cd reactjs-example
npm run build

執行成功後會生成 /build 目錄,直接放到你的服務器上就能展現了~

錄像

create-react-app-build

  • 若是本地打開 build/index.html ,你會發現找不到資源文件,由於默認是指向 / 修改本地容許

先打開模板看下

<!DOCTYPE html>
<html lang="en">
  <head>
    ...
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">

這個 %PUBLIC_URL% 是全局變量

咱們編譯命令要這樣寫

- Windows
set PUBLIC_URL=./ && npm run build

- macOS
PUBLIC_URL=./ npm run build

再次打開 build/index.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  ...
  <link rel="manifest" href="./manifest.json">
  <link rel="shortcut icon" href="./favicon.ico">
  <title>React App</title>
  <link href="./static/css/main.65027555.css" rel="stylesheet">
</head>

替換完成!

本文代碼

參考文

相關文章
相關標籤/搜索