iT邦幫忙

2021 iThome 鐵人賽

DAY 14
0
Modern Web

看初心者怎麼學React系列 第 14

Day14 Custom Hooks

Custom Hooks 是指可以建立一個自訂的個函式,在函式中使用Hook寫出能重複利用的功能,將它模組化,供給不同的元件使用。這樣就不用再不同元件中重複寫同樣邏輯的程式碼了!而元件中的資料依然能獨立不被影響。

命名一個自定義的 Hook 函式是以「use」為開頭的小駝峰命名。
請遵守這個命名規範,這樣才能判斷使用的 function 中是否包含對 Hook 的呼叫。


直接用範例來說明:

我想重複使用一段將台幣根據匯率轉換成日幣的程式碼。

我新增一個customHook.js檔放共用的Hook函式,
只需要import需要的Hook就好,因為Custom Hooks就是在一般函式中使用Hook
函式寫完記得將函式輸出給其他檔案使用唷。

function的命名我使用use+ChangeJPY,讓自訂的函式的回傳轉換過的日幣幣值

./useChangeJPY.js

import { useState,useEffect} from 'react';
//換日幣
function useChangeJPY(twd){

    const [money,setMoney]= useState(null)

    useEffect(() => {
        setMoney(twd*3.9463)
        },[twd])

    return money
}

export default useChangeJPY

接著我在兩個元件中使用customHook:

  • 記得import customHook
  • customHook在React的 function component中使用

在ShowTitle元件中顯示匯率轉換範例文字

./ShowTitle.js

import React from 'react';
import './All.css';
import useChangeJPY from './useChangeJPY.js'

function ShowTitle() {

  const JPY =useChangeJPY(100)

  return (
    <div>       
       <h3>100新台幣 = {JPY}日幣</h3>     
    </div>
)}
export default ShowTitle;

在ChangMoney元件中輸入台幣轉換成日幣

./ChangMoney.js

import React,{useState} from 'react';
import './All.css';
import useChangJPY from './useChangJPY.js'

function ChangMoney() {
  
  const [nt,setNt]=useState(null)

  const JPY =useChangJPY(nt)

  return (
    <div>
       
       <div >台幣:<input type="number" onChange={(event)=> setNt(event.target.value)} /></div>
       <div className="flex">日幣:{JPY}</div>
       
    </div>
    
)}

export default ChangMoney;

在兩個component利用一行函式的code就可以使用轉換匯率的功能啦!

https://ithelp.ithome.com.tw/upload/images/20210929/20140303ajX9NUXGvX.png


上一篇
Day13 Function Component的生命週期 - UseEffect
下一篇
Day15 Hook-useRef
系列文
看初心者怎麼學React30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言