欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

react的hooks的用法詳解

 更新時(shí)間:2020年10月12日 11:28:41   作者:圣京都  
這篇文章主要介紹了react的hooks的用法詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

hooks的作用

它改變了原始的React類的開發(fā)方式,改用了函數(shù)形式;它改變了復(fù)雜的狀態(tài)操作形式,讓程序員用起來更輕松;它改變了一個(gè)狀態(tài)組件的復(fù)用性,讓組件的復(fù)用性大大增加。

useState

// 聲明狀態(tài)
const [ count , setCount ] = useState(0);

// 使用狀態(tài)
<p>You clicked {count} times</p>
<button onClick={()=>{setCount(count+1)}}>click me</button>

useEffect

一個(gè)參數(shù)

useEffect(()=>{
 console.log("首次渲染與更新")
})

模擬:
componentDidMount componentDidUpdate

一個(gè)參數(shù)帶return

useEffect(()=>{
 console.log("首次渲染與更新")
return ()=>{console.log(首次卸載)}
})

 模擬:

  • componentDidMount
  •  componentDidUpdate

return

  •  componetWillUnmount
  •  componentDidUpdate

第二個(gè)參數(shù)是空數(shù)組,return

useEffect(()=>{
 console.log("首次渲染與更新")
return ()=>{console.log(首次卸載)}
},[])

相對(duì)于生命周期的componentDidMount和componetWillUnmount

第二個(gè)參數(shù)是具體的值

useEffect(()=>{
 console.log("首次渲染與更新")
return ()=>{console.log(首次卸載)}
},[num])

模擬

  • componentDidMount
  • componentDidUpdate(update只對(duì)num有用)

return

  •  componetWillUnmount
  •  componentDidUpdate(update只對(duì)num有用)

useRef

const inp = useRef(null)
<input ref={inp}>
//調(diào)用
inp.current.value

自定義hook

定義:const [size,setSize] = useState({height:xxx,width:xxx})

處理:

const onResize = ()=>{setSize({width:xxx,height:xxx})}
 useEffect(()=>{
監(jiān)聽事件 window.addEventListener(“resize”,onResize)
 return 移除監(jiān)聽()=>window.removeEventListener(“resize”,onResize)
 },[])

返回 return size

使用 const size = useWinSize()

到此這篇關(guān)于react的hooks的用法詳解的文章就介紹到這了,更多相關(guān)react hooks用法內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論