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


<<:  【把玩Azure DevOps】Day17 CI/CD从这里:Pipeline设定Schedule,每日晚上排程执行

>>:  [Day25] - Using Redux with Web Component

【从零开始的Swift开发心路历程-Day18】简易订单系统Part2

昨天我们已经成功建立资料库了,今天要做的是将资料存进资料库并且让TableView能马上更新资料库里...

每日挑战,从Javascript面试题目了解一些你可能忽略的概念 - Day18

tags: ItIron2021 Javascript 前言 终於...我们终於可以稍微换个新主题了...

甘特图

甘特图 (Gantt Chart) 是一种条状图,也许是工程师最不想看的图表,通常开发产品、专案都会...

Day10: Detection on AWS

接下来我们将进入到五大面向的第二个部分:侦测。 侦测帮你找出资源的错误配置以及异常的行为,这些找到的...

WordPress 强制使用 https 连线 (使用 SSL 凭证)

在 Google 搜寻公告中,已经将 Https 连线列为重要的网站优化排名之中,拥有 https ...