教你在react中創(chuàng)建自定義hooks
一、什么是自定義hooks
邏輯復(fù)用
簡(jiǎn)單來(lái)說(shuō)就是使用自定義hook可以將某些組件邏輯提取到可重用的函數(shù)中。 自定義hook是一個(gè)從use開(kāi)始的調(diào)用其他hook的Javascript函數(shù)。
二、不使用自定義hook時(shí)
例1:當(dāng)我們整個(gè)頁(yè)面需要獲取用戶(hù)鼠標(biāo)移動(dòng)的坐標(biāo)時(shí),不使用hook的代碼,我們可以這樣寫(xiě)
const [position, setPosition] = useState({ x: 0, y: 0 }) useEffect(() => { const move = (e) => { setPosition({ x: e.x, y: e.y }) } document.addEventListener('mousemove', move) return () => { document.removeEventListener('mousemove', move) } }, []) return ( <div> x:{position.x} y:{position.y} </div> )
例2:當(dāng)我們頁(yè)面中有一個(gè)圖片要跟隨鼠標(biāo)移動(dòng)時(shí),不使用hook的代碼,我們也可以這樣寫(xiě):
const [position, setPosition] = useState({ x: 0, y: 0 }) useEffect(() => { const move = (e) => { setPosition({ x: e.x, y: e.y }) } document.addEventListener('mousemove', move) return () => { document.removeEventListener('mousemove', move) } }, []) return ( <div> <img src={img} style={{ position: 'absolute', top: position.y, left: position.x, }} alt="" /> </div> )
很明顯,以上兩個(gè)例子呈現(xiàn)效果不同,但使用的邏輯代碼大部分相同時(shí),這些邏輯代碼我們就可以使用hook進(jìn)行邏輯復(fù)用
三、使用自定義hook
我們提取以上兩個(gè)例子里可以復(fù)用的邏輯代碼,新建一個(gè)名為useMousePosition的文件
import { useState, useEffect } from 'react' export default function useMousePosition() { const [position, setPosition] = useState({ x: 0, y: 0 }) useEffect(() => { const move = (e) => { setPosition({ x: e.x, y: e.y }) } document.addEventListener('mousemove', move) return () => { document.removeEventListener('mousemove', move) } }, []) return position }
我們?cè)趗seMousePosition函數(shù)中提取了此功能。現(xiàn)在,我們可以將其導(dǎo)入到要使用的任何位置!
最后像使用普通函數(shù)那樣使用即可
const position = useMousePosition() return ( <div> x:{position.x} y:{position.y} </div> )
很明顯使代碼量減少了
到此這篇關(guān)于react中創(chuàng)建自定義hooks的文章就介紹到這了,更多相關(guān)react自定義hooks內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
react中監(jiān)聽(tīng)props的改變方式
這篇文章主要介紹了react中監(jiān)聽(tīng)props的改變方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-01-01React實(shí)現(xiàn)單向數(shù)據(jù)流的方法
本文主要介紹了React實(shí)現(xiàn)單向數(shù)據(jù)流的方法2023-04-04react+antd實(shí)現(xiàn)動(dòng)態(tài)編輯表格數(shù)據(jù)
這篇文章主要為大家詳細(xì)介紹了react+antd實(shí)現(xiàn)動(dòng)態(tài)編輯表格數(shù)據(jù),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-08-08react數(shù)據(jù)管理中的setState與Props詳解
setState?是?React?中用于更新組件狀態(tài)(state)的方法,本文給大家介紹react數(shù)據(jù)管理中的setState與Props知識(shí),感興趣的朋友跟隨小編一起看看吧2023-10-10一篇文章介紹redux、react-redux、redux-saga總結(jié)
這篇文章主要介紹了一篇文章介紹redux、react-redux、redux-saga總結(jié),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-05-05快速創(chuàng)建React項(xiàng)目并配置webpack
這篇文章主要介紹了創(chuàng)建React項(xiàng)目并配置webpack,在這里需要注意,Create?React?App?requires?Node?14?or?higher.需要安裝高版本的node,本文給大家介紹的非常詳細(xì),需要的朋友參考下吧2022-01-01