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:
在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就可以使用转换汇率的功能啦!
<<: 【把玩Azure DevOps】Day17 CI/CD从这里:Pipeline设定Schedule,每日晚上排程执行
>>: [Day25] - Using Redux with Web Component
昨天我们已经成功建立资料库了,今天要做的是将资料存进资料库并且让TableView能马上更新资料库里...
tags: ItIron2021 Javascript 前言 终於...我们终於可以稍微换个新主题了...
甘特图 (Gantt Chart) 是一种条状图,也许是工程师最不想看的图表,通常开发产品、专案都会...
接下来我们将进入到五大面向的第二个部分:侦测。 侦测帮你找出资源的错误配置以及异常的行为,这些找到的...
在 Google 搜寻公告中,已经将 Https 连线列为重要的网站优化排名之中,拥有 https ...