教你在react中創(chuàng)建自定義hooks
一、什么是自定義hooks
邏輯復(fù)用
簡單來說就是使用自定義hook可以將某些組件邏輯提取到可重用的函數(shù)中。 自定義hook是一個從use開始的調(diào)用其他hook的Javascript函數(shù)。
二、不使用自定義hook時
例1:當(dāng)我們整個頁面需要獲取用戶鼠標(biāo)移動的坐標(biāo)時,不使用hook的代碼,我們可以這樣寫
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)我們頁面中有一個圖片要跟隨鼠標(biāo)移動時,不使用hook的代碼,我們也可以這樣寫:
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> )
很明顯,以上兩個例子呈現(xiàn)效果不同,但使用的邏輯代碼大部分相同時,這些邏輯代碼我們就可以使用hook進(jìn)行邏輯復(fù)用
三、使用自定義hook
我們提取以上兩個例子里可以復(fù)用的邏輯代碼,新建一個名為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 }
我們在useMousePosition函數(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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
React實(shí)現(xiàn)單向數(shù)據(jù)流的方法
本文主要介紹了React實(shí)現(xiàn)單向數(shù)據(jù)流的方法2023-04-04react+antd實(shí)現(xiàn)動態(tài)編輯表格數(shù)據(jù)
這篇文章主要為大家詳細(xì)介紹了react+antd實(shí)現(xiàn)動態(tài)編輯表格數(shù)據(jù),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-08-08react數(shù)據(jù)管理中的setState與Props詳解
setState?是?React?中用于更新組件狀態(tài)(state)的方法,本文給大家介紹react數(shù)據(jù)管理中的setState與Props知識,感興趣的朋友跟隨小編一起看看吧2023-10-10一篇文章介紹redux、react-redux、redux-saga總結(jié)
這篇文章主要介紹了一篇文章介紹redux、react-redux、redux-saga總結(jié),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧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