iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 14
1
Modern Web

Zero to hero with React.js系列 第 14

【Day 14 React】React + Webpack ——搜尋功能 #Part3

呈現符合搜尋的結果

首先,我要先把寫死的 Toothpaste 產品資訊替換掉,替換成可以動態塞入符合搜尋結果的程式碼。

Results 這個 component 裡面,我們可以透過 map(),去撈出相符的資料,return 到 DOM 上,這邊加上 key 方便 React 追蹤後續每一個元件的更動。

render(){
      return(
        <div className="results">
          {this.state.foundProducts.map(function(product,i){
            return (
                <Result product={product} key={i}/>
            )
          })}
        </div>
      )
    }
    

建立新的 Result 類別,透過 {this.props.product.name} 取得產品名稱;{this.props.product.price} 取得價格;this.props.product.describe取得產品資訊。

class Result extends React.Component {
render(){
  return(
      <div className="in-stock">
         <h2><a href="">{this.props.product.name}</a></h2>
         <p>{this.props.product.price}</p>
         <p>{this.props.product.describe}</p>
     </div>
  )
}
}

我現在取得的價錢是沒有小數點,我要將它轉換成美金,所以我另外寫了一個 displayPrice() 的 function,把我要計算的數字丟進去除以 100.00

displayPrice(price){
    return (price / 100.00);
}

在 return 使用 this.displayPrice() 呼叫

 <p>${this.displayPrice(this.props.product.price)}</p>
 

Make Component File
寫到這邊功能差不多完成了,不過 component 越切越多,程式也越來越冗長。在 React 裡我們可以把這些 component 拆開,放在不同的檔案裡,這樣能讓我們的程式碼更簡潔,未來能夠更容易維護。
做法是在 app 資料夾底下創一個 component 資料夾,我取的檔名是 search.jsx.jsx 可以讓開發者一目瞭然這是轉譯前的 jsx 檔案

我們在 search.jsx 會用到 React ,所以要引入

var React = require('react');

另外,我們必須透過 module.export 才能從 index.js import

module.exports = Search;

接著回到 index.js 引入

var Search = require('./component/search.jsx');

一路拆到底

剛剛是從 index.js 切分 component 出來,事實上,每一個 component 都可以放在不同的檔案,再透過 module.export 輸出。
因此我把每一個 component 放在專屬於自己的檔案中

  • search.jsx
  • search_bar.jsx
  • result.jsx
  • results.jsx

這邊每一個檔案都要 require

var React = require('react');

同樣的在最後一行也要有輸出動作

module.exports = <Component name>;

特別要注意的是 result.jsx,它是 parent component,所以它不只要引入 React,他還要引入所有的 child component。

專案連結 Github


上一篇
【Day 13 React】React + Webpack ——搜尋功能 #Part2
下一篇
【Day15 React】React Flux 架構介紹
系列文
Zero to hero with React.js30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言