文章

Meteor + ReactJS 學習筆記(二)使用 Semantic UI

上一篇文章是說明怎麼建立一個基本的 Meteor 專案。本篇文章,的目的是紀錄如何在一個 Meteor+ ReactJS 專案中,使用 Semantic UI來建置 UI 元件

Step 1: 建立一個 Meteor project,前端使用 ReactJS

自 Meteor 1.8.0.2 版開始,meteor 中建立專案的指令 meteor create 新增了一個參數 –react,可以讓開發者很容易的就建立一個前端使用ReactJS 的 Meteor 專案
使用以下指令建立名為 meteor-react-hello 的 Meteor 專案

meteor create --react meteor-react-hello
cd meteor-react-hello

Step 2: 安裝 Semantic UI

一個好的 Web 應用,使用者第一眼看到的介面是很重要的,用傳統 HTML做出來的表單、按鈕、對話框…不免讓人覺得網站很老舊的感覺,所以建議還是去找尋比較好的 UI Framework 來使用。UI Framework的選擇很多,如果懶得自己去找,建議可以使用 Semantic UI

從 Atmosphere 安裝 Semantic UI
meteor add semantic:ui
移除 standard-minifier-css
meteor remove standard-minifier-css
安裝 less 與 juliancwirko:postcss
meteor add less juliancwirko:postcss
安裝 Semantic UI for React 及 postcss-load-config
meteor npm install --save semantic-ui-react postcss-load-config posts
修改 package.json,將 postcss 設定加入 package.json

打開 package.json, 加入以下 json code

"devDependencies": {"autoprefixer": "^6.3.1"},"postcss": {
"plugins": {
"autoprefixer": {
"browsers": ["last 2 versions"]
}
}
}

安裝 autoprefixer NPM package
meteor npm install
建立一個空的 custom.semantic.json 檔

custom.semantic.json 使 Semantic UI 的設定檔,用來設定需要載入哪些 UI 元件,原則上就是要使用的元件設為 true,不使用的設為 false。完整的 custom.semantic.json 範例可參考 https://github.com/SilentCicero/meteor-dapp-builder/blob/master/.custom.semantic.json

輸入以下指令,建立一個空的 custom.semantic.json 檔

mkdir -p ./client/lib/semantic-ui
touch ./client/lib/semantic-ui/custom.semantic.json

打開 custom.semantic.json,複製貼上以下的 json code

{
"definitions": {
"site": true,
"container": true,
"button": true,
"segment": true,
"form": true,
"grid": true,
"header": true,
"image": true,
"message": true,
"flag": true
},
"themes": {
"basic": true,
"default": true
}
}

Step 3:啟動 meteor project

輸入以下指令,啟動 meteor 專案

meteor

Step 4:使用瀏覽器打開 Web 應用

使用以下網址打開 Web 應用
http://localhost:3000

你會看到如下圖畫面。這時候 Click Me 按鈕還是用預設的 HTML button,我們必須在程式碼中加入我們要使用的 Semantic UI Button

Step 6: 修改 Hello.jsx

Hello.jsx 的位址在 imports/ui/Hello.jsx

打開 Hello.jsx,在程式的最上方加入以下程式碼,引入 Button 模塊

import { Button } from 'semantic-ui-react'

將程式中原本

<button onClick={() => this.increment()}>Click Me</button>

將 button 改為 Button
<Button onClick={() => this.increment()}>Click Me</Button>

再次瀏覽  http://localhost:3000 ,按鈕已換成 Semantic UI Button 了