React-入門教學第一篇

1.使用node.js 新增一個全新的React專案

1
2
3
npx create-react-app 專案名稱   // 利用npx create-react-app 建構專案 
cd my-app // 移動至專案目錄下
npm start // 啟動

2.建立一個超入門的組件

  1. 先將SRC資料夾底下的檔案全部刪除

  2. 新增Item.js

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    import React, {Component} from 'react';     //載入react核心

    class Item extends Component{ //創建一個Item組件
    render() {
    return(
    <li>Hello, World!</li>
    )
    }
    }

    export default Item;
  3. 新增一個List.js

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    import React, { Component } from 'react';       //載入react核心
    import Item from './Item' //載入Item.js

    class List extends Component{ //創建一個List組件
    render() {
    return(
    <ul>
    <Item/> //使用Item組件
    <Item/>
    <Item/>
    <Item/>
    </ul>
    )
    }
    }

    export default List;
  4. 新增一個index.js(此為預設的進入點,找到所import進來的模組,再下去找其他檔案import的模組)

    1
    2
    3
    4
    5
    6
    7
    8
    import React from 'react';                      //載入react核心
    import ReactDom from 'react-dom'; //載入react-dom核心
    import List from './List'; //載入List.js

    ReactDom.render(<List/>, document.getElementById('root'))
    //render第一個參數是element,第二個參數是DOM container
    //List --> 它是一個class
    //<List/> --> 它是一個元素(object)
  5. 使用 npm run build 打包檔案

  6. 網頁呈現畫面

分享到